##Header file
Manager.h
@interface Manager : NSObject
+ (instancetype)sharedInstance;
@end
##Method file
- Prevent concurrent access from multiple thread by @synchronized or dispatch_once
- Prevent multiple allocation by overriding allocWithZone
Manager.m
@implementation Manager
static Manager *_manager = nil;
+ (instancetype)sharedInstance {
@synchronized(self) {
if(!_manager) {
(void)[[self alloc] init];
}
}
return _manager;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if(!_manager) {
_manager = [super allocWithZone:zone];
}
}
return _manager;
}
@end
or
Manager.m
@implementation Manager
static Manager *_manager = nil;
+ (instancetype)sharedInstance {
static dispath_once_t onceToken;
dispatch_once(&onceToken, ^{
(void)[[self alloc] init];
});
return _manager;
}
+ (id)allocWithZone:(NSZone *)zone {
static dispath_once_t onceToken;
dispatch_once(&onceToken, ^{
_manager = [super allocWithZone:zone];
});
return _manager;
}
@end
##Access
[Manager sharedInstance].property
[[Manager sharedInstance] method];
References
http://qiita.com/yuky_az/items/27031ec5ca55a95d6209
http://programming-ios.com/objective-c-singleton/
http://news.mynavi.jp/column/objc/051/