What happens if the init method of a singleton class is called before the +sharedInstance method..?

时间:2015-06-26 09:53:16

标签: ios objective-c iphone singleton

What happens if the init method of a singleton class is called before the +sharedInstance method..? Will this result in a new object and if not then how the same instance is returned ? The fact that the static variable is declared inside the sharedInstance will have any effect on the overall outcome..?

+ (LibraryAPI*)sharedInstance
{
    // 1
    static LibraryAPI *_sharedInstance = nil;

    // 2
    static dispatch_once_t oncePredicate;

    // 3
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[LibraryAPI alloc] init];
    });
    return _sharedInstance;
}

2 个答案:

答案 0 :(得分:0)

That depends on how the init method is implemented. By default you can create a new object with init. To prevent that an instance of this class is created you could return nil in the init method and create a private initializer for your class.

-(instancetype)init {
    return nil;
}

-(instancetype)localInit {
    if(!self) {
        self = [super init];
    }
    return self;
}

So the line

_sharedInstance = [[LibraryAPI alloc] init];

will change to

_sharedInstance = [[LibraryAPI alloc] localInit];

答案 1 :(得分:0)

In Objective-C init method of a class is just method with 'init' prefix. It's one of the biggest differences between objc and swift. So if you call init method which is bad but you'll no doubt init a new instance when your init method return successfully.

A static variable inside a function keeps its value between invocations. So every time method sharedInstance is called it will give you the same instance. More about static variable check out here