2010-10-12 28 views
6

我试图实现一个类,该子类直接从NSObject开始,只能有一个实例在整个应用程序中都可用。Objective-C创建只有一个实例的类的正确方法

目前我有这种做法:

// MyClass.h 

@interface MyClass : NSObject 

+(MyClass *) instance; 

@end 

和实现:

// MyClass.m 

// static instance of MyClass 
static MyClass *s_instance; 

@implementation MyClass 

-(id) init 
{ 
    [self dealloc]; 
    [NSException raise:@"No instances allowed of type MyClass" format:@"Cannot create instance of MyClass. Use the static instance method instead."]; 

    return nil; 
} 

-(id) initInstance 
{ 
    return [super init]; 
} 

+(MyClass *) instance { 
    if (s_instance == nil) 
    { 
     s_instance = [[DefaultLiteralComparator alloc] initInstance]; 
    } 

    return s_instance;  
} 

@end 

这是为了完成这样的任务的正确方法?

谢谢

回答

7

你需要做的比这更多。这说明一个Objective-C单应如何实现:Objective-C Singleton

+0

谢谢,我会用这个解决方案! – 2010-10-12 01:18:54

+1

另请参阅http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – sdolan 2010-10-12 01:23:21

+0

不错的链接,帮了我很多! – 2010-10-12 01:32:28

0

在您的情况,还有一种方法来创建类的第二个实例:

MyClass *secondInstance = [[MyClass alloc] initInstance]; //we have another instance! 

你需要的是覆盖类的+(id)alloc方法:

+(id)alloc{ 
    @synchronized(self){ 
     NSAssert(s_instance == nil, @"Attempted to allocate a second instance of singleton(MyClass)"); 
     s_instance = [super alloc]; 
     return s_instance; 
    } 
    return nil; 
} 
+0

是的,但'initInstance'方法不在标题中,只在执行中... – 2010-10-12 01:17:14

+0

你会得到一个编译器警告,但就是这样。它仍然会运行,并创建第二个实例。此外,没有任何东西禁止类的方法创建自己的另一个实例。 – executor21 2010-10-12 01:21:50

+0

实际上,你不会得到编译器警告,因为initInstance的定义在它的唯一用途之前。 – JeremyP 2010-10-12 09:45:04

相关问题