Clicky

iOS Dev Nugget 309 Rule of Thumb Regarding self.

.

Need to run a code review on your codebase? Hire me

I have some guidelines I apply to myself to help reduce cyclic references caused by closures capturing self.

  1. I never explicitly refer to self (as in self.someProperty or self.someFunc()) unless I absolutely have to.
  2. I have a simple rule of thumb, if I see a self. in a closure, I double check to make sure it is necessary. This is because self. in a closure means the closure captures self and holds a strong reference to self. Most of the time, this can lead to cyclic references either now or later. I try my best to avoid them.

Because of (1) above, self. will only appear:

  1. in init() and its variations
  2. when I need to assign to a new local variable in a function and the new local variable has the same name as a function or a property
  3. when closure captures self.

This means I can run grep -R "self\." . and do a quick scan when I suspect a memory leak.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues