【问题标题】:Blocks and GCD: Asynchronous data collection块和 GCD:异步数据收集
【发布时间】: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


    【解决方案1】:

    异步做某事时,需要触发“嘿,我已经下载数据了!”来自异步执行的代码。

    也就是说,加载数据的块的末尾会执行以下操作:

     dispatch_async(dispatch_get_main_queue(), ^{
          ... do whatever is necessary to load/display the data in the UI here ...
     });
    

    【讨论】:

      【解决方案2】:

      我能否提供一个可以大大简化您的生活的建议 - 使用 AFNetworking 进行此类网络操作。

      或者,您需要将一个回调块传递给您的函数,然后该函数可以使用weatherData 值执行。您对weatherData 错误的假设是正确的。

      【讨论】:

        【解决方案3】:

        我建议发布一个 NSNotification,然后为该通知设置一个侦听器,并在那时在 weatherData 上执行必要的代码。

        虽然我最喜欢@bbum 的建议。

        【讨论】:

          猜你喜欢
          • 2014-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 1970-01-01
          • 2021-10-24
          • 1970-01-01
          • 2013-07-19
          相关资源
          最近更新 更多