从异步代码块返回NSDictionary? [英] Returning NSDictionary from async code block?
本文介绍了从异步代码块返回NSDictionary?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
从块中返回UIImage
您好我正在尝试返回字典json twitter数据,所以我可以在我的应用程序中使用它。怎么从异步块调用它。我无法保存或回复任何想法?
Hi I'm trying to return dictionary of json twitter data so i can use it in my application. How ever it is being called from a async block. I can not save it or return it any thoughts?
-(NSDictionary *)TweetFetcher
{
TWRequest *request = [[TWRequest alloc] initWithURL:
[NSURL URLWithString: @"http://search.twitter.com/search.json?
q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"] parameters:nil
requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse
*urlResponse,
NSError *error)
{
if ([urlResponse statusCode] == 200)
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:0 error:&error];
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:@"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog([NSString stringWithFormat:@"%@", [internalDict
objectForKey:@"from_user_name"]]);
----> return dict; // i need this dictionary of json twitter data
}
else
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
Thnx提前!
推荐答案
我觉得我最近写了很多这样的异步代码。
I feel like I've written a ton of this async code lately.
- (void)tweetFetcherWithCompletion:(void(^)(NSDictionary *dict, NSError *error))completion
{
NSURL *URL = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"];
TWRequest *request = [[TWRequest alloc] initWithURL:URL parameters:nil requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
completion(nil, error);
return;
}
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:@"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog(@"%@", [internalDict objectForKey:@"from_user_name"]);
completion(dict, nil);
}
else {
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
completion(nil, error);
}
}];
}
所以,而不是调用 self.tweetDict = [自我TweetFetcher];
,你会这样称呼它。
So, instead of calling self.tweetDict = [self TweetFetcher];
, you would call it this way.
[self tweetFetcherWithCompletion:^(NSDictionary *dict, NSError *error) {
if (error) {
// Handle Error Somehow
}
self.tweetDict = dict;
// Everything else you need to do with the dictionary.
}];
这篇关于从异步代码块返回NSDictionary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文