Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly implement ARC compatible and `alloc init` safe Singleton class? [duplicate]

I saw thread safe version

+(MyClass *)singleton {
    static dispatch_once_t pred;
    static MyClass *shared = nil;

    dispatch_once(&pred, ^{
        shared = [[MyClass alloc] init];
    });
     return shared;
}

but what would happen if someone just calls [MyClass alloc] init] ? How to make it return same instance as the +(MyClass *)singleton method?

like image 885
Dulguun Otgon Avatar asked Jul 23 '13 11:07

Dulguun Otgon


1 Answers

Apple recommends the strict singleton implementation (no other living object of the same type is allowed) this way:

+ (instancetype)singleton {
    static id singletonInstance = nil;
    if (!singletonInstance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            singletonInstance = [[super allocWithZone:NULL] init];
        });
    }
    return singletonInstance;
}

+ (id)allocWithZone:(NSZone *)zone {
    return [self singleton];
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

Link to the apple documentation (bottom of page, Without ARC)

like image 80
Jonathan Cichon Avatar answered Nov 12 '22 13:11

Jonathan Cichon