简体   繁体   English

如何在 iPhone 的 objective-c 中实现 singleton

[英]how to implement singleton in objective-c for iphone

i want to make my object singleton in the iPhone application.What is the proper way of implementing this in objective-c.我想在 iPhone 应用程序中制作我的 object singleton。在 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.这并不能阻止人们意外创建非 singleton 实例,但我认为最好设计您的 class 以便非单身人士不会破坏 class 而不是试图阻止非单身人士。 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. Singleton 类是一个需要理解的重要概念,因为它们展示了一种非常有用的设计模式。 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.这个想法在整个 iPhone SDK 中被使用,例如,UIApplication 有一个名为 sharedApplication 的方法,当从任何地方调用它时,将返回与当前运行的应用程序相关的 UIApplication 实例。

Implement Singleton Classes in Objective- C.在 Objective-C 中实现 Singleton 类。

I use the one written by matt gallagher http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html .我使用的是 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虽然我不是很喜欢 C 宏,但我觉得这种基于宏的 singleton 综合方法非常棒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM