1

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;
}
nr5
  • 4,228
  • 8
  • 42
  • 82

2 Answers2

1

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;
}
Michael
  • 6,561
  • 5
  • 38
  • 55
  • 1
    If someone by mistake does not use sharedManager method of yours and does alloc init, it wont be a singleton anymore... – nr5 Mar 04 '15 at 07:23
  • This question addresses your comment - http://stackoverflow.com/questions/7274360/how-objective-c-singleton-should-implement-init-method – Michael Mar 04 '15 at 07:31
1

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.

Tonny Xu
  • 2,162
  • 2
  • 16
  • 20
  • So alloc calls the ovveridern allocwithzone in my code but [super allocWithZone:] does not ? – nr5 Mar 04 '15 at 07:39
  • No, seams you didn't understand the inheritance. `super` will call your `allocWithZone:` because you override it. You call `super alloc`, `super alloc` calls your `allocWithZone:`. When you call `super allocWithZones` it will not call your `allocWithZone:` – Tonny Xu Mar 04 '15 at 07:40