如何在Objective-C中为iPhone实现单例 [英] how to implement singleton in objective-c for iphone

查看:57
本文介绍了如何在Objective-C中为iPhone实现单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iPhone应用程序中使对象成为单例.在Objective-c中实现此目标的正确方法是什么.

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

推荐答案

这是我的方法.

+(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.

这篇关于如何在Objective-C中为iPhone实现单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆