Created
February 27, 2015 04:44
-
-
Save cdzombak/375683efae61b68a159c to your computer and use it in GitHub Desktop.
simple ObjC lazy getter macro
This file contains 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 <Foundation/Foundation.h> | |
#define lazy_get(TYPE, NAME, VALUE) \ | |
@synthesize NAME = _##NAME; \ | |
- (TYPE)NAME { if (!_##NAME) _##NAME = (VALUE); return _##NAME; } | |
// example usage follows: | |
@interface LazyThing : NSObject | |
@property (nonatomic, readonly) NSString *lazyString; | |
@property (nonatomic, copy) NSString *aString; | |
@end | |
@implementation LazyThing | |
lazy_get(NSString *, lazyString, { | |
NSString *a = @"a"; | |
NSString *b = @"b"; | |
[a stringByAppendingString:b]; | |
}) | |
lazy_get(NSString *, aString, { | |
NSString *x = @"x"; | |
[x stringByAppendingString:[@(1) stringValue]]; | |
}) | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment