profile for monkeydom at Stack Overflow, Q&A for professional and enthusiast programmers

cocoa-dom

coding bits I use, come across, like, hate, the whole shebang.

twitter | github      rant-dom         rss | archive

Permalink
Home

Blocks need considering

While I don't agree with this post in most respects, it still alerted me to a crucial thing when using blocks: Be sure the Macros you use in them don't reference self directly. And if they do and you need to be sure to not create a retain cycle, use either @weakify and @strongify from libextobjc or do shadow self yourself this way:

__weak typeof(self) weakSelf = self; 

// some api that takes blocks, when you give the block do 
^{
    __strong typeof(weakSelf) self = weakSelf; 
}

So thanks for ranting so much to alert me to the fact that NSAssert() does reference self directly, and as such make the block retain self.

Update: ZAssert seems to be a reasonable replacement for NSAssert() in blocks which is mentioned in the comments of the Article.

Update 2: Since this is such a common pattern, I've seen people using welf instead of weakSelf, which makes me chuckle. Also the __typeof__ can be replaced by typeof, which makes it less atrocious.