我在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) –