开发者

how to implement singleton in objective-c for iphone

开发者 https://www.devze.com 2023-03-15 23:15 出处:网络
i want to mak开发者_开发技巧e my object singleton in the iPhone application.What is the proper way of implementing this in objective-c.Here\'s how I do it.

i want to mak开发者_开发技巧e my object singleton in the iPhone application.What is the proper way of implementing this in objective-c.


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.


Taken from

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.

Implement Singleton Classes in Objective- C .


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消