Senseful Senseful - 3 months ago 12
Swift Question

Should I use [weak self] in PromiseKit blocks?

PromiseKit states the following on their website:


Should I be concerned about retain cycles?



tl;dr: it’s safe to use self in promise handlers.

This is safe:

somePromise.then {
self.doSomething()
}


Provided
somePromise
resolves, the function passed to
then
will be released, thus specifying
[weak self]
is not necessary.

Specifying [unowned self] is likely dangerous.

You’re telling me not to worry about retain cycles?!



No, it’s just that by default you are not going to cause retain cycles when using PromiseKit. But it is still possible...


Does this mean I should never use
[weak self]
in PromiseKit blocks? Are there ever situations where I would still need to use
[weak self]
? How exactly is it preventing a retain cycle?

Rob Rob
Answer

That documentation is merely saying that you don't have to worry about PromiseKit introducing "strong reference cycles" (previously known as "retain cycles") because when the promise is fulfilled and the block finishes running, those strong references are automatically resolved for you. The choice of strong vs weak references is solely up to you.

For example, there's no need to keep a strong reference to a dismissed view controller if you are simply updating UI elements on scene that no longer exists. You'd use weak in that scenario. But sometimes you want strong reference (e.g. you may want to update the underlying model to reflect the success or failure of the promise).

Bottom line, all they're saying is that you shouldn't let PromiseKit dictate the strong vs weak references, but rather it should be driven by your app's broader design requirements. The only hard rule re PromiseKit is that you should avoid unowned.

Comments