简体   繁体   English

这样安全吗? Singleton上可能的保留周期为自成块

[英]Is This Safe? Possible Retain Cycle on Singleton as Self in Block

I'm pretty sure this is 100% safe, but I don't want to miss anything. 我很确定这是100%安全的,但是我不想错过任何东西。 I have the following code 我有以下代码

- (void) scheduleControlSurfaceProcess {
    [self.operationQueueForMessageProcessing addOperationWithBlock:^{
        // do something
        [self scheduleControlSurfaceProcess];     
    }];
}

where self is a Singleton. 自我是一个单例。 The block works splendidly as a non-main-thread thread. 该块作为非主线程出色地工作。 I do not see any memory problems in the profiler (which I don't trust much). 我在探查器中看不到任何内存问题(对此我不太信任)。

So, may I ignore the warning, "Block will be retained by an object strongly retained by the captured object?" 因此, 我可以忽略警告:“块将被捕获的对象强烈保留的对象保留吗?” If not, how can I insist that the block to get released (with ARC)? 如果不是,我如何坚持要释放该块(使用ARC)? Getting the warning to go away is easy enough, but assigning id what = self seems like it would not solve the problem. 消除警告很容易,但是给id what = self分配id what = self似乎并不能解决问题。

EDIT : as I realized quite late in this question, the real problem here was that I am rescheduling from within the block itself. 编辑 :正如我在这个问题中很晚才意识到的那样,这里的真正问题是我正在从块本身内部重新计划。 This is obviously problematic, because each block retains the next. 这显然是有问题的,因为每个块都保留下一个。

NOTE: I am aware that there are lots of questions on this topic , but I'm not expert enough to know which, if any, situations are similar to this one. 注意:我知道关于此主题很多问题 ,但是我不足以知道哪种情况与该情况类似。

- (void) scheduleControlSurfaceProcess {
    __weak id SELF = self;
    [self.operationQueueForMessageProcessing addOperationWithBlock:^{
        id strongSelf = SELF; //Guarantee self doesn't go away in the meantime
        // do something
        [self.operationQueueForMessageProcessing addOperationWithBlock:^{
            [strongSelf scheduleControlSurfaceProcess]; 
        }];
    }];
}

That would guarantee you won't have a cycle here. 那将保证您不会在这里有一个循环。 The warning is completely valid, self retains the operation queue, the queue retains the block, the block retains self. 警告是完全有效的,自身保留操作队列,队列保留块,块保留自身。 And round and round we go. 一圈又一圈地走。

In my modified example the block will capture SELF and store it into 'strongSelf'. 在我的修改示例中,该块将捕获SELF并将其存储到“ strongSelf”中。 The strongSelf step isn't strictly necessary, but it will make sure the reference to self doesn't get niled during execution of the block. strongSelf步骤不是严格必需的,但是它将确保在执行该块期间不会对self的引用产生干扰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM