how to implement singleton in objective-c for iphone

廉价感情. 提交于 2019-12-14 02:37:16

问题


i want to make my object singleton in the iPhone application.What is the proper way of implementing this in objective-c.


回答1:


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.




回答2:


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 .




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6518512/how-to-implement-singleton-in-objective-c-for-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!