完成块的返回结果

所以我试图在Twitter API(为其他项目)之上构build一个图层,并且需要find一种方法将Twitter操作的结果返回到抽象层。

现在我的设置是这样的,例如:

-(NSDictionary *)sendTweet:(Tweet *)tweet { __block NSMutableDictionary *responseDictionary; NSLog(@"Sending tweet"); NSMutableDictionary *twitterRequestDictionary = [[NSMutableDictionary alloc] init]; [twitterRequestDictionary setObject:tweet.tweetBody forKey:@"status"]; TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"] parameters:twitterRequestDictionary requestMethod:TWRequestMethodPOST]; [request setAccount:self.userAccount]; [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; NSLog(@"Response dictionary: %@", responseDictionary); return responseDictionary; }]; 

}

但是因为'performRequestWithHandler:'方法返回'void',所以最后一行会导致错误。

我也尝试在块之外放置“return”语句,并在发现这篇文章后locking代码块的执行: http : //omegadelta.net/2011/05/10/how-to-wait-换IOS的方法,以完成块到结束

仍然没有运气。

我希望有人可以通过这种方式来做到这一点(或者build议一个更好的方法来返回数据)。

你为什么不使用块来返回响应? 就像是:

 -(void)sendTweet:(Tweet *)tweet withResponseCallback:(void (^)(NSMutableDictionary *responseDictionary))callback { NSLog(@"Sending tweet"); NSMutableDictionary *twitterRequestDictionary = [[NSMutableDictionary alloc] init]; [twitterRequestDictionary setObject:tweet.tweetBody forKey:@"status"]; TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"] parameters:twitterRequestDictionary requestMethod:TWRequestMethodPOST]; [request setAccount:self.userAccount]; [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil]; NSLog(@"Response dictionary: %@", responseDictionary); callback(responseDictionary); }]; } 

由于您正在使用asynchronous方法,所以很难说您的方法何时会返回数据。 所以你可以考虑其他选项来返回结果。 例如,发布通知,发送消息,设置一些属性甚至显示警报视图可能是有用的。

至于文章的代码示例,我会尝试如下所示

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSData *data = [self loadDataWithConditionLock]; dispatch_async(dispatch_get_main_queue(), ^{ [self updateUIWithData:data]; }); });