Ric*_*III 6 initialization objective-c
我正在尝试直接实现一个类,即NSObject在使用它的应用程序运行的整个过程中只能有一个实例可用.
目前我有这种方法:
// MyClass.h
@interface MyClass : NSObject
+(MyClass *) instance;
@end
Run Code Online (Sandbox Code Playgroud)
并实施:
// 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
Run Code Online (Sandbox Code Playgroud)
这是完成这项任务的正确方法吗?
谢谢
| 归档时间: |
|
| 查看次数: |
3342 次 |
| 最近记录: |