To keep things simple, no low level Objective-C runtime function calls, just using GCD/blocks, minimal override and base protocol methods implementation.
Easy and Clean.
@interface DDSingleton : NSObject
+ (DDSingleton *)sharedInstance;
@end
@implementation DDSingleton
+ (DDSingleton *)sharedInstance {
static DDSingleton *sharedInstance = nil;
static dispatch_once_t pred;
if (sharedInstance) return sharedInstance;
dispatch_once(&pred, ^{
sharedInstance = [[super allocWithZone:NULL] init];
});
return sharedInstance;
}
// Controlling Instantiation
+ (id)allocWithZone:(NSZone *)zone {
return [[self sharedInstance] retain];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (NSUInteger)retainCount {
return NSUIntegerMax;
}
- (void)release {
}
- (id)autorelease {
return self;
}
@end
If you’re interested in singleton unit testing, please check Peter Hosey’s great work: PRHEmptySingleton. By the way, his test case #6 is very cool.
Running over Peter Hosey’s singleton unit tests, overrelease this singleton won’t cause a crash, which makes test case #4 a NG.
You’ve been informed.
loading…