【问题标题】:Changing @property value of self while executing a block that uses a strong reference to self在执行使用对 self 的强引用的块时更改 self 的 @property 值
【发布时间】:2014-02-21 23:49:08
【问题描述】:

我正在我的应用程序中处理网络请求,并在 NSOperationQueue 中使用 NSBlockOperations 来异步执行此操作。但是,如果调用它们的视图控制器被释放(已从导航堆栈中弹出),我希望能够取消这些操作。

这是我所拥有的简化版本:

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.isCancelled 设置为NO 时,我是否还为块中使用的strongSelf 引用设置了self.isCancelled

【问题讨论】:

    标签: ios asynchronous objective-c-blocks nsblockoperation strong-references


    【解决方案1】:

    selfweakSelfstrongSelf 都指向内存中的同一个对象。这意味着如果您在dealloc(通过设置该属性)中向self 发送消息,weakSelfstrongSelf 也会“知道”这个更新后的属性。所以,是的,你也在strongSelf 上设置self.isCancelled(很可能实际属性的名称是self.cancelled,它的getter 是isCancelled)。

    【讨论】:

    • 感谢您的快速回复。我认为是这样,但缺乏扎实的知识来支持它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多