Question about singleton


#1

I’m alittle confused about the singleton and wondering if i missed something.
Now in the implementation of the class method defaultStore, we have

if (!defaultStore)
{
// Create the singleton
defaultStore = [[super allocWithZone:NULL] init];
}

Now, the creation of the singleton, particularly the super is kinda confusing me
In the book it actually mentions this, but at least for me, it’s not clear.

From the book

I was thinking, isn’t [self allocWithZone:nil] the one we want? By using super, isn’t that telling the compiler that the search for the method should begin at the superclass and proceed up the tree?


#2

Using a singleton, we want to prevent a new instance from being allocated. So, if PossessionStore is ever sent alloc, it should just return the single instance of PossessionStore instead of a new one.

However, the implementation of alloc just calls [self allocWithZone:nil]. So, if we overrode alloc, someone could just circumvent that by calling [PossessionStore allocWithZone:nil] to get a new object.

Therefore, we override allocWithZone: to return the single instance.

If you were to use [self allocWithZone:nil] here, you’d be returned the single instance pointed to by defaultStore. That variable starts out as nil, so you’d always get nil back and never be able to create an object.

By jumping up to the superclass’ implementation, we actually get a new object.


#3

[quote=“JoeConway”]If you were to use [self allocWithZone:nil] here, you’d be returned the single instance pointed to by defaultStore. That variable starts out as nil, so you’d always get nil back and never be able to create an object.

By jumping up to the superclass’ implementation, we actually get a new object.[/quote]
I am not sure that I understand this correctly. Isn’t calling [self allocWithZone:nil] equaling [self defaultStore] in your overridden allocWithZone implementation? That would cause a indefinite loop, right? Please elaborate this a little bit more.


#4

Yup, it would create an infinite loop. By calling super, we skip past that infinite loop.