[英]Return Result of Completion Block
因此,我正在嘗試在項目的Twitter API(以及其他)之上構建一個層,我需要找到一種方法將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'語句,並在發現本文后鎖定代碼塊部分的執行: http : //omegadelta.net/2011/05/10/how-to-wait-換IOS的方法,以完成塊到結束
仍然沒有運氣。
我希望有人可以通過這種方式來解決這個問題(或者建議一種更好的方法來返回數據)。
你為什么不用塊來返回響應? 就像是:
-(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);
}];
}
由於您使用的是異步方法,因此很難說您的方法何時返回數據。 因此,您可以考慮其他選項來返回結果。 例如,發布通知,發送消息,設置某些屬性甚至顯示警報視圖可能很有用。
至於文章的代碼示例,我會嘗試類似以下內容
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [self loadDataWithConditionLock];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUIWithData:data];
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.