2012-08-07 40 views
0

我最近添加線程到應用程序,以便網絡請求不會阻止用戶界面。在這樣做的時候,我發現我不能再像實施線程之前那樣設置實例變量了。我的實例變量是一個屬性聲明如下:實例變量和線程與GCD

@property (nonatomic, strong) NSMutableArray *currentTopPlaces; 

這裏是我如何正確設置我的實例變量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]; 
    }); 

使用[自currentTopPlace] setArray:topPlaces]在運行良好阻止版本,在我開始使用GCD之前。

現在,我必須將它像這樣的事情才能正常工作:

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; 
    }); 

有人能向我解釋兩者的區別:

[[self currentTopPlaces] setArray:topPlaces]; 

和:

self.currentTopPlaces = topPlaces; 

具體而言,爲什麼「setArray」調用在螺紋塊中不起作用?

我認爲Objective-C中的點符號是語法糖而不是強制性的。我想知道實現相同行爲的「不含糖」的方式。

+0

你是什麼意思的「沒有工作」?請具體說明。 – 2012-08-07 21:23:10

回答

5

[self currentTopPlaces]self.currentTopPlaces實際上是相同的,但

[self.currentTopPlaces setArray:topPlaces]; // (1) 
self.currentTopPlaces = topPlaces; // (2) 

沒有。 (1)將self.currentTopPlaces中的所有元素替換爲topPlaces中的所有元素。 (2)爲self.currentTopPlaces分配新值(如果不是,則釋放舊值)。如果self.currentTopPlaces發生

的差:(1)不執行任何操作,因爲setArray:方法被髮送到。 (2)給self.currentTopPlaces分配一個新值。

Btw:代碼中不需要__block修飾符,因爲該塊不會更改topPlaces的值。

2
[[self currentTopPlaces] setArray:topPlaces]; 
self.currentTopPlaces = topPlaces; 

這是兩個完全不同的表達式。首先是因爲寫的,第二個是:

[self setCurrentTopPlaces:topPlaces]; 

如果你想要做的第一個用點符號,這將是:

self.currentTopPlaces.array = topPlaces; 
+0

謝謝,我現在看到了區別,但我想我仍然不明白爲什麼setArray看起來在非線程版本中「工作」,但不是在線程版本中。 setArray文檔說:「將接收數組的元素設置爲另一個給定數組中的元素..」使用setCurrentTopPlaces時,它是否也將它的元素設置爲另一個數組的元素 - 在這種情況下是topPlaces?當使用setCurrentTopPlaces時,除此之外還必須發生其他事情,對吧? – 2012-08-07 21:17:06

+0

@FabrizioMachado:在線程版本中,'setArray'究竟做了些什麼? – 2012-08-07 21:25:30

+0

@MartinR:在調用setArray之後,currentTopPlaces在線程版本中仍然是空的。 – 2012-08-07 21:27:08