请先尝试存根self.topPlaces
这样的:
dispatch_queue_t downloadQueue = dispatch_queue_create("flickr topPlace", NULL);
dispatch_async(downloadQueue, ^{
NSArray *topPlaces = [FlickrFetcher topPlaces];
dispatch_async(dispatch_get_main_queue(), ^{
self.topPlaces = @[@"test", @"test2", @"test3"];
});
});
然后检查self.topPlaces
值。如果它仍然是NULL
那么我需要问你的财产self.topPlaces
有什么终身限定符(例如强,弱,转让)?如果它是weak
那么当然topPlaces
的值将是NULL
,因为不会有任何强的指针指向它。如果是strong
,则当执行到达self.topPlaces = topPlaces;
时,NSArray *topPlaces = [FlickrFetcher topPlaces];
的值为NULL
。
要考虑的另一件事是,当您执行异步操作时,主线程上的执行将继续执行。所以,如果你正在做以下...
dispatch_queue_t downloadQueue = dispatch_queue_create("flickr topPlace", NULL);
dispatch_async(downloadQueue, ^{
NSArray *topPlaces = [FlickrFetcher topPlaces];
dispatch_async(dispatch_get_main_queue(), ^{
self.topPlaces = topPlaces;
});
});
NSLog(@"topPlaces = %@", self.topPlaces);
然后我希望self.topPlaces
永远是NULL
当它击中NSLog
由于它不会被设置到后[FlickrFetcher topPlaces]
已经完成并返回与执行继续进入dispatch_async(dispatch_get_main_queue()...
。此时应该设置值。您可能需要执行以下操作,以确保您不仅设置属性,还会在异步操作完成后执行某种更新操作以更新UI ...
dispatch_queue_t downloadQueue = dispatch_queue_create("flickr topPlace", NULL);
dispatch_async(downloadQueue, ^{
NSArray *topPlaces = [FlickrFetcher topPlaces];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUIWithTopPlaces:topPlaces];
});
});
- (void)updateUIWithTopPlaces:(NSArray*)topPlaces {
self.topPlaces = topPlaces;
// Perform your UI updates here
}
您究竟在哪里检查自我.topPlaces? – BergQuester
这段代码被放到viewDidLoad中,我是'NSLog',它也在viewDidLoad上面的代码之后。此外,如果它不是NULL,我的视图会显示一些内容,但目前它没有显示任何内容。 – Enzo
ut是异步代码在FlickrFetcher代码运行之前的调度之后运行的'NSLOg'ing。 – zaph