質問

Is there any shorter version? It feels like a lot of boilerplate.

I'm throwing in a couple of examples where I think it is tedious

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static id instance;
    dispatch_once(&onceToken, ^{
        instance = [self new];
    });
    return instance;
}

+ (NSString *)RFC2822StringFromDate:(NSDate *)date
{
    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [NSDateFormatter new];
        formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss Z";
    });

    return [formatter stringFromDate:date];
}
役に立ちましたか?

解決

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;\
})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top