我将应用程序代码移动到MVC模型,因此我创建了一种从API检索某些数据的方法。
+ (NSMutableArray *)loadFromFeed {
NSString *feed = @"https://api.test.com";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:feedUrl]];
request = [mutableRequest copy];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [JSONResponseSerializerWithData serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonArray = (NSArray *)[responseObject objectForKey:@"items"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
CLS_LOG(@"Error");
}];
}
现在,理想情况下,我希望将jsonArray
作为此方法的一部分返回。但是,由于AFHTTPRequestOperation
是异步的,我不知道如何解决此问题,仍然可以在应用中的任何位置调用[Data loadFromFeed];
。我怎么能这样做?
答案 0 :(得分:2)
你可以将名为success和failure的两个块传递给loadFromFeed
,
然后从setCompletionBlockWithSuccess
成功和失败块中调用两个块,将jsonArray传递给成功块:
typedef void (^Success)(id data);
typedef void (^Failure)(NSError *error);
- (void)loadFromFeed:(Success)success failure:(Failure)failure;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *jsonArray = (NSArray *)[responseObject objectForKey:@"items"];
success?success(jsonArray):nil;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure?failure(error):nil;
}];
然后以这种方式使用:
[Data loadFromFeed:^(id data) {
NSLog(@"%@",data)
} failure:^(NSError *error) {
NSLog(@"%@",error)
}];];