Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 1.53 KB

weak-reference-issue.md

File metadata and controls

33 lines (29 loc) · 1.53 KB

Weak Reference Issue

We often used __weak to prevent the retain cycle problem in a block, but it occurs another issue that weak variable would be nil if the object pointed originally by weak variable released during we use it in block. To fix this , we declare one more variable in block to to retain the weak variable:

__weak typeof(self) weakSelf = self;
[self.APIService fetchRequest:request withCompletionBlock:
^(NSArray *infoList){
    typeof(self) strongSelf = weakSelf;
    if(strongSelf){
        // do the callback work
    } else {
        // do nothing
        // It is still possible that strongSelf
        // get nil from weakSelf
    }
}];

NOTE:
According to the comment in stackoverflow,

Keep in mind the strong reference cycle may not be this straightforward. For example, if your controller has a strong reference to an object, that object has a strong reference to a completion block, and then the completion block strongly references your controller, you'll still have a retain cycle, just with 3 objects instead of 2

We should need to check retain cycle with more care by this reminder.

Reference