【发布时间】:2013-04-08 19:10:29
【问题描述】:
我从 JSON(对 Web 服务完全陌生)开始,我这样做是为了从 Wunderground API 收集数据。这个同步代码对我有用:
NSDictionary *weatherData;
NSString *urlString;
if (self.apiKey) {
urlString = [@"http://api.wunderground.com/api/" stringByAppendingString:self.apiKey];
}
urlString = [urlString stringByAppendingString:@"/conditions/q/CA/San_Francisco.json"];;
NSURL *url = [NSURL URLWithString:urlString];
NSData *jasonData = [NSData dataWithContentsOfURL:url];
NSError *error;
weatherData = [NSJSONSerialization JSONObjectWithData:jasonData options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON Object, error description = %@", [error localizedDescription]);
}
return weatherData;
// returns a dictionary
但这不是:
__block NSDictionary *weatherData;
dispatch_queue_t weatherDataQueue = dispatch_queue_create("weatherDataQueue", NULL);
dispatch_async(weatherDataQueue, ^{
NSString *urlString;
if (self.apiKey) {
urlString = [@"http://api.wunderground.com/api/" stringByAppendingString:self.apiKey];
}
urlString = [urlString stringByAppendingString:@"/conditions/q/CA/San_Francisco.json"];;
NSURL *url = [NSURL URLWithString:urlString];
NSData *jasonData = [NSData dataWithContentsOfURL:url];
NSError *error;
weatherData = [NSJSONSerialization JSONObjectWithData:jasonData options:0 error:&error];
if (error) {
NSLog(@"Error with creating JSON Object, error description %@", [error localizedDescription]);
}
});
NSLog(@"weatherData = %@", weatherData);
return weatherData;
// returns NULL
现在,我意识到这可能与当我返回weatherData 时,已调度块中的代码尚未运行有关。
如果有人能帮我弄清楚如何解决这个问题,我将不胜感激。
【问题讨论】:
标签: objective-c objective-c-blocks grand-central-dispatch