#import "SingletonObject.h"
@implementation SingletonObject
//宣告一個靜態的Singleton物件
static SingletonObject *_singletonObject = nil;
- (id)init {
self = [super init];
if (self) {
//將 count 初始化為0
count = 0;
}
return self;
}
//執行時會判斷是否 _singletonObject 已經完成記憶體配置
+ (SingletonObject *)sharedSingletonObject {
@synchronized([SingletonObject class]) {
//判斷_singletonObject是否完成記憶體配置
if (!_singletonObject)
[[self alloc] init];
return _singletonObject;
}
return nil;
}
+ (id)alloc {
@synchronized([SingletonObject class]) {
//避免 [SingletonObject alloc] 方法被濫用
NSAssert(_singletonObject == nil, @"_singletonObject 已經做過記憶體配置");
_singletonObject = [super alloc];
return _singletonObject;
}
return nil;
}
- (void)addCount {
count += 1;
}
- (void)showCount {
NSLog(@"%d", count);
}
- (void)dealloc {
[super dealloc];
}
@end
沒有留言:
張貼留言