TL;DR: Continue using [weak self]
in PromiseKit blocks to prevent objects from living longer than necessary.
There are a few things to note. First, there are 2 primary reasons to use [weak self]
in a block:
- Prevent retain cycles
- Prevent objects living longer than necessary
Second, PromiseKit is creating a retain cycle when you call that block of code. self
is holding on to somePromise
usually, and somePromise
is holding on to self
. The reason that they say you shouldn't be concerned with this retain cycle is because the retain cycle is going to get broken automatically by PromiseKit. When then
is released, somePromise
will no longer hold on to self
, thus breaking the retain cycle.
So we know we don't need to worry about problem #1 with PromiseKit blocks, but what about problem #2?
Imagine a view controller fires off a network request promise and that it's going to take 30 seconds until this promise is resolved. Now before it's resolved, the user presses the back button. Normally UIKit is going to deallocate the view controller since it is no longer on screen and the system can save resources. However, since you referenced self
in the promise, it can no longer be deallocated. This means the view controller is going to live 30 seconds longer in memory than is necessary.
The only way to resolve problem #2 is by using [weak self]
inside the block.
Note: One could argue that when your view controller backs out, you should cancel the ongoing promise anyways so that it releases the hold on self
. However, figuring out when a view controller should be deallocated is not a simple task. It's much easier to let UIKit handle the logic for you and if you do indeed need to do anything when a view controller is deallocated, implementing it in the view controller's dealloc
method. This won't work if the block is holding on to the view controller strongly.
Update: Looks like one of the authors did talk about this and clarified the reasons for making those recommendations:
In fact, retaining self
is probably what you want so to allow the promise to resolve before self
is deallocated.