devdoe
devdoe

Reputation: 4325

Avoiding singletonton abuse in objective C

I have created a singleton:

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    NSAssert(FALSE, @"Please use getSharedInstance class method of MotionManager to avoid singleton abuse. =)");

    return nil;
}


+ (id) getSharedInstance
{
    if (!instance)
    {
        instance = [[super allocWithZone:NULL] init];
    }

    return instance;
}

Why does the above works fine, but the below one throws exception?

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    NSAssert(FALSE, @"Please use getSharedInstance class method of MotionManager to avoid singleton abuse. =)");

    return nil;
}


+ (id) getSharedInstance
{
    if (!instance)
    {
        instance = [[super alloc] init];
    }

    return instance;
}

Upvotes: 1

Views: 87

Answers (2)

Tonny Xu
Tonny Xu

Reputation: 2162

This is because alloc is also calling allocWithZone: internally, see NSObject doc

That's the reason why your code instance = [[super allocWithZone:NULL] init]; works while instance = [[super alloc] init]; doesn't.

Upvotes: 1

Michael
Michael

Reputation: 6899

This is the proper way to create a singleton:

+ (id)sharedManager {


    static Singleton *sharedManager = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedMyManager = [[self alloc] init];

    });

    return sharedManager;
}

Upvotes: 1

Related Questions