最近我读别人的代码,看到他写的单例模式修改了retain, release:
- C/C++ code
- (id)retain{ return self; }- (unsigned)retainCount{ return UINT_MAX; //denotes an object that cannot be released}- (oneway void)release{ //do nothing}- (id)autorelease{ return self; }- (void)dealloc { [_sharedManager release]; [super dealloc];}
请问这样做是否必要呢?另外,如何让这个类只能调用shardInstance,而不让别人调用alloc init呢?
------解决方案--------------------
- C/C++ code
+(AppropriateSingleton *) sharedAppropriateSingleton { @synchronized (self) { if (instance_ == nil) {// instance_ = [[super allocWithZone:NULL] init]; // OR instance_ = [NSAllocateObject([self class], 0, NULL) init]; } } return instance_;}+(id) allocWithZone:(NSZone *)zone { @synchronized (self) { return [[self sharedAppropriateSingleton] retain]; }}-(id) copyWithZone:(NSZone *) zone { return self;}