(instancetype)sharedStore


#1

Why did we go through all this code writing when we could of just overrided the init? Instead we created three different methods
1.+ (instancetype)sharedStore
2.-(instancetype)init
3.-(instancetype)initPrivate

Also why is the first one a global method? I guess we did all this is so we can only allow the programmer to use only the global method?

Thanks


#2

First, please note that class methods (indicated by a leading ‘+’ in the method declaration) and scope (“global”) are completely different.

As for why “all of the code” was written…remember that the entire goal of that class was to ensure that multiple instances of the class could not be created. If the application wanted to use the store, then by gosh, there would be only one.

  • (instancetype) sharedStore
    is what we tell the world to use by publishing it the class’s header file. That method ensures that only a single instance of the store exists.
  • (instancetype) init
    is overridden so anyone trying to use it to create multiple instances of the class gets an exception preventing this.

  • (instancetype) initPrivate
    is not published in the header (so it’s “secret”) but is used as the real initializer. While its function COULD conceivably have been incorporated into +sharedStore, that’s not advisable since: (1) it breaks the convention of having init methods NAMED init-something (and as you’ve seen, Objective-C is all about conventions), and (2) the code is cleaner by having the init method stand on its own. You’ll thank yourself months down the road for keeping it separate rather than having to hunt for the initializer.