Created
April 2, 2011 19:08
-
-
Save mikelikespie/899774 to your computer and use it in GitHub Desktop.
Fun way to memoize with blocks. It would be sweet if objc had decorators.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _MEMO(iVarName, block) ^{if (!iVarName) {iVarName = (block)();} return iVarName;} | |
- (UIButton *)eatCheeseButton; | |
{ | |
return _MEMO(eatCheeseButton, ^{ | |
return [[UIButton alloc] init]; | |
})(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure why it's necessary for the macro to return a block, since all you're doing with it is executing it immediately… (I could be missing something).
You could also do this without macros (if you're willing to step into C++):
Of course, you can do it slightly less-nicely and less safely without C++, by means of pointers to
void*
pointers (I hope I did this right):