Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Should we use weak self within block or assign weak self to strong before using it?

As we know, using strong self within a block can lead to retain cycles and memory leak. Is the common practice to use weak self in a block, or is it better to assign the weak self to strong within the block and then use it as such so the weak self is not released during block execution? Does it matter since weak self will be zero-ed out anyway?

like image 376
Boon Avatar asked Dec 14 '22 23:12

Boon


1 Answers

Due to the volatile nature of weak variables, you should use them with care. If you are using weak variables in a multithreading environment, it is considered good practice to assign the weak variable to a strong one and check for nil before using. This will ensure that the object will not be released in the middle of your method, causing unexpected results.

Consider the following case:

__weak id var;

//...

if(var != nil)
{
    //var was released here on another thread and there are not more retaining references.
    [anotherObj performActionWithAnObjThatMustNotBeNil:var]; //<- You may crash here.
}

The compiler can be configured to throw a warning on a consecutive access of a weak variable.

On the other hand, if your use is in the main thread, and all calls to the object are on the main thread, this problem is moot, since the object will either be released before the block call or after, thus it being safe to access the weak variable directly.

like image 81
Léo Natan Avatar answered Jan 19 '23 00:01

Léo Natan