4

所以我试图在一个项目的 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- for-ios-methods-with-completion-blocks-to-finish

仍然没有运气。

我希望有人可以对这种方式有所了解(或者可能建议一种更好的方法来返回数据)。

4

2 回答 2

8

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

-(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);
    }];
}
于 2012-08-23T16:17:14.963 回答
0

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

至于文章的代码示例,我会尝试以下内容

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *data = [self loadDataWithConditionLock];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateUIWithData:data];
    });
});
于 2012-08-23T18:49:57.150 回答