Monday, June 1, 2015

@weakify and @strongify Macros

Arkadiusz Holko:

Original implementation of @weakify and @strongify macros is complex because they accept more than one parameter. To make the analysis simpler, we’ll introduce our own versions, accepting only one parameter each:

#define weakify(var) __weak typeof(var) AHKWeak_##var = var;

#define strongify(var) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
__strong typeof(var) var = AHKWeak_##var; \
_Pragma("clang diagnostic pop")

[…]

In the block, self is overshadowed by a local variable with the same name. Then, self can be used safely inside the block, because it references that local variable, which is held strongly, but lives only until the block ends executing. Even the code not written by us can use self safely, e.g. NSAssert macro.

1 Comment RSS · Twitter


[…] Previously: @weakify and @strongify Macros. […]

Leave a Comment