Sourabh Mahna
Sourabh Mahna

Reputation: 52

Why singleton object is made through class methods?

We always make singleton object through Class method.What will happened if i make that method instance(use - instead of +) and call that method through a nil object or simply through an object?

Upvotes: 0

Views: 45

Answers (1)

Jack
Jack

Reputation: 133577

Conceptually a the instance method is not attached to any specific instance of a class.

This means that from a design point of view it doesn't make sense to invoke it on an existing object. It's like requiring that a +(int) sum:(int)a with:(int)b should be an instance method when it doesn't need to know anything about an object.

In addition usually a singleton class constructor shouldn't be accessible from clients, if you need to instantiate one to call -instance on it this would defeat the purpose.

Last thing, a singleton should be the only possible instance of an object, if you need to have one to instantiate one then you are in a deadlock: you need an instance to create an instance but you are no allowed to have more than an instance.

Regarding calling it on nil object, if I remember correctly a pointer returned from a message sent to nil will always be nil too.

Upvotes: 2

Related Questions