简体   繁体   中英

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. 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)? Getting the warning to go away is easy enough, but assigning id what = self seems like it would not solve the problem.

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'. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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