Skip to content

Instantly share code, notes, and snippets.

@mikelikespie
Created April 2, 2011 19:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikelikespie/899774 to your computer and use it in GitHub Desktop.
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.
#define _MEMO(iVarName, block) ^{if (!iVarName) {iVarName = (block)();} return iVarName;}
- (UIButton *)eatCheeseButton;
{
return _MEMO(eatCheeseButton, ^{
return [[UIButton alloc] init];
})();
}
@jonsterling
Copy link

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++):

template <typename T>
T memoize(T& ivar, T(^block)())
{
  if (ivar == nil) { ivar = block(); }
  return ivar;
}

- (UIButton *)eatCheeseButton
{
  return memoize(eatCheeseButton, ^{
    return [[UIButton alloc] init];
  });
}

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):

void *memoize(void **ivar, void *(^block)())
{
  if (*ivar == nil) { *ivar = block(); }
  return *ivar;
}

- (UIButton *)eatCheeseButton
{
  return memoize(&eatCheeseButton, ^{
    return [[UIButton alloc] init];
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment