块执行后返回null的变量 [英] Variable returning null after block execution

查看:107
本文介绍了块执行后返回null的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调度一个队列,在一个单独的线程上下载一些flickr照片(在viewWillAppear中)。当我在块中记录数组的内容时,它会完美地显示所有内容:

I am dispatching a queue to download some flickr photos on a separate thread (in viewWillAppear). When I log the contents of the array inside the block, it shows everything perfectly:

    dispatch_queue_t photoDowonload=dispatch_queue_create("photoDownload", NULL);
dispatch_async(photoDowonload, ^{

    NSArray *photoList=[FlickrFetcher topPlaces]; //downloads flickr data
    self.listOfCities=photoList;
    NSLog(@"inside block: %@", self.listOfCities); //shows contents

});

但是当我尝试记录在块外部的块内设置的数组时,它返回null 。

but when I try to log the array that was set inside the block outside the block, it returns null.

    dispatch_queue_t photoDowonload=dispatch_queue_create("photoDownload", NULL);
dispatch_async(photoDowonload, ^{

    NSArray *photoList=[FlickrFetcher topPlaces];
    self.listOfCities=photoList;

});

    NSLog(@"after block: %@", self.listOfCities); //returns null

这里有什么问题? self.listOfCities设置为NSArray属性,因此一旦在块中设置它,它应该可以在它之外访问。

What's the problem here? self.listOfCities is set up as NSArray property so once it's set in the block, it should be accessible outside of it.

推荐答案

块中的代码是异步运行的。所以块之后的代码在块中的代码有机会运行之前运行(或者至少肯定完成)。

The code in the block is run asynchronously. So the code after the block is run before the code in the block has had a chance to run (or certainly complete at least).

这篇关于块执行后返回null的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆