How does this code for creation of singleton work?


#1

I have some experience of programming in Java and Python. I am absolutely confused by code for creation of singleton, which first appears in Camera chapter and then MCVS chapter.

It goes like this.

  • (BNRFeedStore *)sharedStore
    {
    static BNRFeedStore *feedStore = nil;
    if(!feedStore)
    {
    feedStore = [[BNRFeedStore alloc]init];
    }
    return feedStore;
    }

My reading of code is like this,

  1. Assign feedstore to nil
  2. Check if feedstore is not assigned to any object
  3. if not then allocate and initialise new object and point feedstore to that object
  4. return feedstore

Why is there an assignment to nil at the very beginning of code? Won’t second “if condition” be always true after that? If that is the case then we are returning a pointer to new/different object each time, how is this singleton then?

What am I missing? I feel like I am missing something very basic here.


#2

Without me simply reiterating what someone has already discussed on this matter, I will point you to this page from Matt Galloway, which describes singletons very well http://www.galloway.me.uk/tutorials/singleton-classes/

Nick
http://myfirstiphoneapp.co.uk


#3

[quote]What am I missing? I feel like I am missing something very basic here.
[/quote]
A static variable is initialised only once.

+ (BNRFeedStore *)sharedStore
{
   static BNRFeedStore *feedStore = nil;
   if (!feedStore)
   {
      feedStore = [[BNRFeedStore alloc]init];
   }
   return feedStore;
}

The very first time the method executes, the value of the feedStore variable is nil and as a result a new object is created and assigned to it. From there on, its value remains intact until you change it again. Initialisation to nil is done behind the scenes and only once.

The following code is easier to understand and is equivalent to the code above, except that it uses a global static variable.

static BNRFeedStore *feedStore = nil;

+ (BNRFeedStore *)sharedStore
{
   if (!feedStore)
   {
      feedStore = [[BNRFeedStore alloc]init];
   }
   return feedStore;
}

#4

Yup, my understanding of “static” was from Java which operates differently than Obj-C.
Thanks a lot for clarification.