Fab*_*ado 0 multithreading objective-c grand-central-dispatch ios5
我最近添加了线程到应用程序,以便网络请求不会阻止UI.在这样做时,我发现我无法再像实现线程之前那样设置我的实例变量.我的实例变量是一个声明如下的属性:
@property (nonatomic, strong) NSMutableArray *currentTopPlaces;
Run Code Online (Sandbox Code Playgroud)
以下是我错误地设置我的实例变量self.currentTopPlaces的方法:
dispatch_queue_t downloadQueue = dispatch_queue_create("Flickr Top Places Downloader", NULL);
dispatch_async(downloadQueue, ^{
__block NSArray *topPlaces = [FlickrFetcher topPlaces];
dispatch_async(dispatch_get_main_queue(), ^{
self.tableRowCount = [topPlaces count];
[[self currentTopPlaces] setArray:topPlaces];
});
Run Code Online (Sandbox Code Playgroud)
在我开始使用GCD之前,使用[self currentTopPlace] setArray:topPlaces]在阻止版本中运行良好.
现在,为了让事情正常工作,我必须这样设置:
dispatch_queue_t downloadQueue = dispatch_queue_create("Flickr Top Places Downloader", NULL);
dispatch_async(downloadQueue, ^{
__block NSArray *topPlaces = [FlickrFetcher topPlaces];
dispatch_async(dispatch_get_main_queue(), ^{
self.tableRowCount = [topPlaces count];
self.currentTopPlaces = topPlaces;
});
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释使用之间的区别:
[[self currentTopPlaces] setArray:topPlaces];
Run Code Online (Sandbox Code Playgroud)
和:
self.currentTopPlaces = topPlaces;
Run Code Online (Sandbox Code Playgroud)
具体来说,为什么"setArray"调用在线程块中不起作用?
我认为Objective-C中的点符号是语法糖而不是强制性的.我想知道实现相同行为的"非加糖"方式.
[self currentTopPlaces]
并且self.currentTopPlaces
实际上是相同的,但是
[self.currentTopPlaces setArray:topPlaces]; // (1)
self.currentTopPlaces = topPlaces; // (2)
Run Code Online (Sandbox Code Playgroud)
不是.(1)用self.currentTopPlaces
来自的那些元素替换所有元素topPlaces
.(2)赋予一个新值self.currentTopPlaces
(如果它不是零,则释放旧值).
如果self.currentTopPlaces
为nil则会出现差异 :(1)什么都不做,因为该setArray:
方法被发送到nil.(2)赋予新值self.currentTopPlaces
.
顺便说一句:__block
代码中没有必要使用修饰符,因为该块不会更改值topPlaces
.
归档时间: |
|
查看次数: |
606 次 |
最近记录: |