ang*_*okh 2 design-patterns objective-c ios
我在objective-c书上看到了一个单例.但是,我不知道在objective-c和其他lang之间是否存在'singleton'定义的含义不同.这个[[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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5284 次 |
| 最近记录: |