i want to make my object singleton in the iPhone application.What is the proper way of implementing this in objective-c.
-
can i know why vote down. is there any error in my question please. – Hariprasad Jun 29 '11 at 10:18
-
4It wasnt me, who down voted you, but most likely because this questions is answered some dozen times in SO. (May I introduce: The Searchbox ↗) – vikingosegundo Jun 29 '11 at 10:23
4 Answers
Here's how I do it.
+(MyClass*) mySingleton
{
static MyClass* theSignleton = nil;
@synchronized([MyClass class])
{
if (theSingleton == nil)
{
theSingleton = [[MyClass alloc] init];
}
}
return theSingleton;
}
That doesn't stop people from accidentally creating non singleton instances but I think it's better to design your class so that non singletons don't break the class rather than trying to stop non singletons. It makes them easier to handle in unit tests.

- 84,577
- 15
- 123
- 161
Singleton classes are an important concept to understand because they exhibit an extremely useful design pattern. This idea is used throughout the iPhone SDK, for example, UIApplication has a method called sharedApplication which when called from anywhere will return the UIApplication instance which relates to the currently running application.

- 34,792
- 12
- 100
- 110

- 31,697
- 9
- 72
- 76
I use the one written by matt gallagher http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html. Its very simple to use and the blog post is a sort of complete tutorial.

- 10,355
- 2
- 43
- 69
Although I don't like C-macros very much, I find this macro-based singleton synthesizing approach remarkable

- 52,040
- 14
- 137
- 178