Wednesday, November 20, 2013

NSNotificationCenter With Blocks Considered Harmful

Great post from Drew Crawford:

This could be, I think, the single biggest API blunder in iOS. (Except maybe iCloud Core Data.) I have debugged issues that were root-caused to this misleading API more than ten times. I have lost more than four weeks to this API. I have no less than six radars open about it.

[…]

The documentation lists no fewer than six sample code projects underneath the Notifications-with-blocks API. And five out of six Apple model projects are wrong. Let that sink in.

It’s exacerbated by documentation bugs/omissions, such as that NSAssert should not be used in blocks. He links to two alternative APIs, FXNotifications (which uses swizzling) and NSNotificationCenter-JNWBlocks (which uses associated objects). Both use weak object references, which means they won’t work on Mac OS X 10.6.

3 Comments RSS · Twitter

Blocks are great for continuations, where you use the block to tell what to do next, but bad for reactive callbacks where your objects just want to update itself when something changes. You need to be meticulously careful about the later.

There should be a syntax for creating blocks with a weak reference to self. Let's say:

^[__weak self]{ ... }

Then it'll still be easy to forget to make it weak when you should, but at least it'll be easy to fix when found.

[…] Previously: NSNotificationCenter With Blocks Considered Harmful. […]

[…] Previously: NSNotificationCenter With Blocks Considered Harmful. […]

Leave a Comment