0

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;
}
Ankit Srivastava
  • 12,347
  • 11
  • 63
  • 115
  • Look at this SO [question](http://stackoverflow.com/questions/7274360/how-objective-c-singleton-should-implement-init-method) – Fabio Felici Jun 26 '15 at 10:05
  • Your question is not clear to me. If I call [[LibraryAPI alloc] init] 5 times, it will create and return 5 objects. But If I call [LibraryAPI sharedInstance] it will always return the singleton object. – swapnilagarwal Jun 26 '15 at 10:16

2 Answers2

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];
Marco
  • 1,276
  • 1
  • 10
  • 19
  • 1
    in this case wouldn't the line "_sharedInstance = [[LibraryAPI alloc] init];" also receive nil as return..? – Ankit Srivastava Jun 26 '15 at 10:08
  • You're right! I'll remove the code example. Basically you could write another init method, which is not accessible from outside your class --> I update my answer. – Marco Jun 26 '15 at 10:10
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

Community
  • 1
  • 1
dopcn
  • 4,218
  • 3
  • 23
  • 32