Created
January 3, 2014 06:59
-
-
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.
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
#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 |
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 NNMemoize(block) _NNMemoize(self, _cmd, block) | |
id _NNMemoize(id self, SEL _cmd, id (^block)()); |
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
#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