Taking Notes

cause i'll forget

Making NSAssert Play Nice With Blocks

NSAssert is actually a macro that calls NSAssertionHandler using the handleFailureInMethod:object:file:lineNumber:description method with self as the argument for object. This is fine and dandy for most asserts, but if you’re in a block, you probably just made a retain cycle.

Luckily this is pretty easy to fix by logging the function instead of the object:

#if !defined(NS_BLOCK_ASSERTIONS)

#define BlockAssert(condition, desc, ...) \
do {\
if (!(condition)) { \
[[NSAssertionHandler currentHandler] handleFailureInFunction:NSStringFromSelector(_cmd) \
file:[NSString stringWithUTF8String:__FILE__] \
lineNumber:__LINE__ \
description:(desc), ##__VA_ARGS__]; \
}\
} while(0);

#else // NS_BLOCK_ASSERTIONS defined

#define BlockAssert(condition, desc, ...) 

#endif

This new macro behaves the same and will compile out with the same flags as NSAssert.

Easy, Peasy.