我在一个类(静态方法)中有以下代码,我调用该类从API获取数据。我决定把它作为一个静态方法,这样我就可以在应用程序的其他部分重用它。
+ (NSArray*) getAllRoomsWithEventId:(NSNumber *)eventId{
NSURL *urlRequest = [NSURL URLWithString:[NSString stringWithFormat:@"http://blablba.com/api/Rooms/GetAll/e/%@/r?%@", eventId, [ServiceRequest getAuth]]];
NSMutableArray *rooms = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:urlRequest];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Response of getall rooms %@", JSON);
NSArray *jsonResults = (NSArray*)JSON;
for(id item in jsonResults){
Room* room = [[Room alloc]init];
if([item isKindOfClass:[NSDictionary class]]){
room.Id = [item objectForKey:@"Id"];
room.eventId = [item objectForKey:@"EventId"];
room.UINumber = [item objectForKey:@"RoomUIID"];
[rooms addObject:room];
}
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(@"Error");
}];
[operation start];
[operation waitUntilFinished];
return rooms;
}
现在我的问题是,每当我在ViewController(ViewDidLoad方法)中调用它时。静态方法将运行到最后,并在房间上返回null,但Nslog将在几秒钟后显示"成功"块Nslog。现在我知道这是异步的,所以它不会等到成功块执行后才到达"return rooms;"行。话虽如此,我需要一些关于如何处理这件事的建议,比如进度条之类的?或者是什么东西耽误了它?我真的不确定这是不是再运输的方式,或者如果是,我不确定该怎么做。
非常感谢您的任何建议。非常感谢。
AFNetworking是围绕异步性构建的——启动一个请求,然后在该请求完成后执行一些代码。
waitUntilFinished
是一种反模式,它可以阻塞用户界面。
相反,您的方法应该没有返回类型(void)
,并且有一个返回序列化的房间数组的完成块参数:
- (void)allRoomsWithEventId:(NSNumber *)eventId
block:(void (^)(NSArray *rooms))block
{
// ...
}
有关如何做到这一点的示例,请参阅AFNetworking项目中的示例应用程序。
您可以按照以下方式编写方法:
+ (void) getAllRoomsWithEventId:(NSNumber *)eventId:(void(^)(NSArray *roomArray)) block
{
NSURL *urlRequest = [NSURL URLWithString:[NSString stringWithFormat:@"http://blablba.com/api/Rooms/GetAll/e/%@/r?%@", eventId, [ServiceRequest getAuth]]];
NSMutableArray *rooms = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:urlRequest];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"Response of getall rooms %@", JSON);
NSArray *jsonResults = (NSArray*)JSON;
for(id item in jsonResults){
Room* room = [[Room alloc]init];
if([item isKindOfClass:[NSDictionary class]]){
room.Id = [item objectForKey:@"Id"];
room.eventId = [item objectForKey:@"EventId"];
room.UINumber = [item objectForKey:@"RoomUIID"];
[rooms addObject:room];
}
}
block(rooms);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(@"Error");
block(nil); //or any other error message..
}];
[operation start];
[operation waitUntilFinished];
}
你可以这样调用这个方法:
[MyDataClass getAllRoomsWithEventId:@"eventid1":^(NSArray *roomArray) {
NSLog(@"roomArr == %@",roomArray);
}];