当前位置: 代码迷 >> Iphone >> objc的单例有关问题
  详细解决方案

objc的单例有关问题

热度:99   发布时间:2016-04-25 06:43:57.0
objc的单例问题
最近我读别人的代码,看到他写的单例模式修改了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;}