Skip to content

Instantly share code, notes, and snippets.

@numist
Created January 3, 2014 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numist/8233973 to your computer and use it in GitHub Desktop.
Save numist/8233973 to your computer and use it in GitHub Desktop.
Result memoization for object values that are both immutable and expensive to compute.
#import "memoize.h"
@implementation Example
- (id)null;
{
return NNMemoize(^{
sleep(1);
return [NSNull null];
});
}
- (NSRect)computedFrame;
{
return [NNMemoize((^{
NSPoint min = [self.viewCollection lastObject].frame.origin,
max = [self.viewCollection lastObject].frame.origin;
for (NSView *view in self.viewCollection) {
min.x = MIN(min.x, window.frame.origin.x);
min.y = MIN(min.y, window.frame.origin.y);
max.x = MAX(max.x, window.frame.origin.x + window.frame.size.width);
max.y = MAX(max.y, window.frame.origin.y + window.frame.size.height);
}
return [NSValue valueWithRect:(NSRect){.origin = min, .size.width = max.x - min.x, .size.height = max.y - min.y}];
})) rectValue];
}
@end
#define NNMemoize(block) _NNMemoize(self, _cmd, block)
id _NNMemoize(id self, SEL _cmd, id (^block)());
#include "memoize.h"
id _NNMemoize(id self, SEL _cmd, id (^block)()) {
id result;
void *key = (void *)((uintptr_t)(__bridge void *)self ^ (uintptr_t)(void *)_cmd ^ (uintptr_t)&_NNMemoize);
@synchronized(self) {
result = objc_getAssociatedObject(self, key);
if (!result) {
result = block();
objc_setAssociatedObject(self, key, result, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment