weakSelf not _always_ needed in iOS and ObjC, right?

59 Views Asked by At

Help me resolve a tiny argument with a colleague. Weak self is not needed in this circumstance, right?

(He doesn't believe me)

__weak auto weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    [weakSelf _someHelper];
});
2

There are 2 best solutions below

0
On BEST ANSWER

Correct, it is not always needed in cases like this. We often wouldn’t bother with this syntactic noise in this situation.

If it was dispatch_after or if this dispatch back to the main queue was buried inside some asynchronous call, then there’s an argument for weakSelf pattern (so you don’t keep strong reference longer than might be needed), but in your simple example, dispatching immediately to the main queue, the weak reference to self is not needed.

That having been said, it’s not wrong to adopt weakSelf pattern here. Just unnecessary.


The question in my mind is that if you’re dispatching back to the main queue, that suggests you are in the middle of something time consuming on some background queue. In that case, then refraining from keeping strong reference to self may well be prudent. We can’t say without seeing the broader context of where you are performing this code.

0
On

Note that ARC (automatic reference counter) can lead to situation where strong references will create a cycle. Such cycle will lead to memory leak (reference counter will never reach zero). In languages where garbage collection is available such cycle can be detected by gc and memory will be freed.

Now weak pointer prevent creation of permanent cycle of strong references.

Presented example is to general to tell if this is necessary or not.

There are some cases where some other object is responsible for object lifetime and invocation of _someHelper should be prevented when strong referees from other objects has expired (for example there action is not needed any more). In this case you need weak self.

In other case you need warranty that _someHelper is executed even if all other objects has lost contact with this object, so in such case you need that dispatch queue holds strong reference to object. In this case weak self is obsolete.