gpt4 book ai didi

objective-c - 完成 block 的返回结果

转载 作者:可可西里 更新时间:2023-11-01 06:25:22 26 4
gpt4 key购买 nike

因此,我正尝试在 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”语句放在 block 外并锁定代码块部分的执行:http://omegadelta.net/2011/05/10/how-to-wait-for-ios-methods-with-completion-blocks-to-finish

仍然没有运气。

我希望有人能阐明这种方法(或者可能建议一种更好的方法来返回数据)。

最佳答案

为什么不也使用 block 来返回响应?像这样的东西:

-(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);
}];
}

关于objective-c - 完成 block 的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12095784/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com