在仔細研究單身人士文學之後,下面是我編造的。 我忘了什麼嗎?這是權威參考計算Objective C單例實現?
@implementation MySingleton
static MySingleton *mySharedInstance = nil;
//called by atexit on exit, to ensure all resources are freed properly (not just memory)
static void singleton_remover()
{
//free resources here
}
+ (MySingleton*) sharedInstance{
return mySharedInstance;
}
+ (void)initialize {
if (self == [MySingleton class]) {
mySharedInstance = [[super allocWithZone:NULL] init];
atexit(singleton_remover);
}
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (NSUInteger)retainCount
{
return NSUIntegerMax; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
請不要編輯您的問題的方式,使現有的答案無效或不再相關。 – dreamlax 2010-02-19 04:19:02
爲什麼另一個Objective-C單例線程?有關示例,請參閱http://stackoverflow.com/questions/145154。 – zoul 2010-02-19 06:52:24
難道你只是使用加拉格爾的http://projectswithlove.com/projects/SynthesizeSingleton.h.zip從http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html。 ..? – Fattie 2010-12-23 19:39:01