There was a really good post on the Black Pixel blog by Rich Wardwell about the implications of capturing self
in Objective-C blocks which Brent Simmon’s posted a response to on his blog. If you’re lost, I’m talking about doing this sort of thing to avoid retain cycles:
__weak MyClass *weakSelf = self;
self.someObject.blockProperty = ^{
weakSelf.someProperty = something;
};
Brent’s thoughts/rules for blocks partially mimic my own1. I never use -[NSNotificationCenter addObserverForName:queue:usingBlock:]
; I just don’t see the benefit. Unlike Brent, it’s not uncommon for me to copy a block and assign it to a property, but usually if I start having more than one or two somethingHandler
blocks, creating a delegate protocol is a better fit most of the time (this code also tends to be easier to debug). I also agree that thinking about if self
really needs to be used in the block at all is a good practice (Rich also mentions this).
I can’t say why exactly, but whenever I have to the whole weakSelf
thing, it feels like I’m doing something wrong – it seems like kind of a code smell. That’s not to say I never do it (I do it all the time), but my general feeling is that if I need to, I should probably think about if I’m approaching this from the right angle.
-
One difference. At some point recently I realized I'd memorized the crazy block syntax:
BOOL(^someBlock)(NSString *string)
. I'm not too proud of this, since I'm pretty sure it points to some kind of underlying psychological disorder ↩