1

我正在做我的应用程序中的网络请求,并且正在NSOperationQueue中使用NSBlockOperations以异步执行此操作。但是,如果调用它们的视图控制器已被释放(已从导航堆栈中弹出),我希望能够取消这些操作。在执行一个使用自我强引用的块时更改self的@property值

这是什么,我有一个简化版本:

NSArray *posts; 

__weak DataController *weakSelf = self; 
NSBlockOperation *fetchPostsOperation = [NSBlockOperation blockOperationWithBlock:^{ 
    DataController *strongSelf = weakSelf; 
    NSDictionary *response = [weakSelf refreshPostsInPart:PartFirst]; 
    posts = [response objectForKey:@"posts"]; 
}]; 

[self.queue addOperation:fetchPostsOperation]; 

在DataController类的refreshPostsInPart:方法我为使用while循环从App.net拼版数据网络的重复请求。在循环的每次迭代中,我检查DataController self.isCancelled(BOOL类型)的属性,如果它是NO我不断发出请求。

在我的DataController的dealloc方法中,我将此属性设置为YES,以便在while循环的下一次迭代中,我将停止发出请求。实质上,我在使用NSBlockOperation时实现了一个可怜的男人cancelAllOperations

问题:当在我的dealloc方法中设置self.isCancelledNO时,我是否也在设置self.isCancelled作为block中使用的strongSelf引用?

回答

2

self,weakSelfstrongSelf全都指内存中的同一个对象。这意味着如果您发送消息selfdealloc(您通过设置该属性),weakSelfstrongSelf也“知道”此更新的属性。所以,是的,你也在strongSelf上设置了self.isCancelled(很可能实际的房产名称是self.cancelled,其获取者是isCancelled)。

+0

感谢您的快速响应。我认为这是事实,但缺乏坚实的知识来支持它。 –

相关问题