繁体   English   中英

完成块的返回结果

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM