Skip to content

Instantly share code, notes, and snippets.

@halsk
Created April 5, 2013 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halsk/5316908 to your computer and use it in GitHub Desktop.
Save halsk/5316908 to your computer and use it in GitHub Desktop.
Objective-C で継承可能な Singleton Class を作る ref: http://qiita.com/items/b4e51c33e7c9d29964ab
SingletonA *s1 = [SingletonA sharedInstance];
[s1 printA]; // 'NSInvalidArgumentException', reason: '-[Singleton printA]: unrecognized selector sent to instance が発生
SingletonA *s1 = [SingletonA sharedInstance];
[s1 printA];
SingletonB *s2 = [SingletonB sharedInstance];
[s2 printB];
@implementation Singleton
static NSMutableDictionary *_instances;
+ (id) sharedInstance {
__block Singleton *obj;
@synchronized(self) {
if ([_instances objectForKey:NSStringFromClass(self)] == nil) {
obj = [[self alloc] initSharedInstance];
}
}
obj = [_instances objectForKey:NSStringFromClass(self)];
return obj;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if ([_instances objectForKey:NSStringFromClass(self)] == nil) {
id instance = [super allocWithZone:zone];
if ([_instances count] == 0) {
_instances = [[NSMutableDictionary alloc] initWithCapacity:0];
}
[_instances setObject:instance forKey:NSStringFromClass(self)];
return instance;
}
}
return nil;
}
- (id)initSharedInstance {
self = [super init];
if (self) {
// do something
}
return self;
}
- (id)init {
[self doesNotRecognizeSelector:_cmd]; // init を直接呼ぼうとしたらエラーを発生させる
return nil;
}
- (void)print{
NSLog(@"hoge");
}
@end
@interface SingletonA : Singleton
-(void)printA;
@end
@interface SingletonB : Singleton
-(void)printB;
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment