我在objective-c书上看到了一个singleton示例。但是,我不知道在objective-c和其他langs之间是否存在“singleton”定义的不同含义。这个[[SingletonClass alloc] init]仍然可以用来创建一个新的对象吗?如果是,如何保证内存中只有一个对象?singleton in objective c
#import "SingletonClass.h"
@implementation SingletonClass
static SingletonClass *sharedInstance = nil;
// Get the shared instance and create it if necessary.
+ (SingletonClass*)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
// We can still have a regular init method, that will get called the first time the Singleton is used.
- (id)init
{
self = [super init];
if (self) {
// Work your initialising magic here as you normally would
}
return self;
}
可能的复制:[目的-C:静态字段和执行单例模式](http://stackoverflow.com/questions/6912703/objective-c-static-field-and-implementation-singleton-pattern/6913036#6913036) –