且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Objective-C中为iPhone实现单例

更新时间:2022-12-04 12:31:06

这是我的方法.

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