I just made a small macro which basically lets you write quite short stuff
+ (instancetype)sharedInstance
{
return dispatch_once_and_return(id, [self new]);
}
Also blocks is supported with this semantic
+ (NSString *)altRFC2822StringFromDate:(NSDate *)date
{
NSDateFormatter *formatter = dispatch_once_and_return(NSDateFormatter *, ^{
NSDateFormatter *f = [NSDateFormatter new];
// setup formatter
return f;
}());
return [formatter stringFromDate:date];
}
(The trick is to add ()
after the block, which basically executes the block right away).
The macro
#define dispatch_once_and_return(type, value) ({\
static type cachedValue;\
static dispatch_once_t onceToken;\
dispatch_once(&onceToken, ^{\
cachedValue = value;\
});\
cachedValue;\
})