我在一本Objective-C书中看到了一个单例模式的例子。然而,我不知道'单例'定义在Objective-C和其他语言中是否有意义上的区别。[[SingletonClass alloc] init]仍然可以用来创建新对象吗?如果是,如何保证内存中只有一个对象?
#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;
}