单例-b

这个比较老了,是mrc 里面的

此例以模仿Apple官方文档的单例写出来的。但是一直有一个非常不明白的地方,就是alloc与allocWithZone:的重载中,为什么要return [[self currentEnvironment] retain];,而不是return [self currentEnvironment];。

有的朋友认为alloc, copy在这个单例中没有意义,因为alloc会再次的调用allocWithZone, copy会调用copyWithZone。但是为了保险起见,我仍然保留了alloc,喜欢刨根问底的朋友可以查阅一些相关的资料。

苹果的官方文档   单例的例子在文档最后。

@implementation LXYEnvironment

static LXYEnvironment *_environment=nil;

#pragma mark- 单例模式

+ (LXYEnvironment *)currentEnvironment

{

    @synchronized(self)

    {

        if (!_environment)

        {

            _environment=[[super allocWithZone:NULL] init];

        }

    }

    return _environment;

}

 

+ (id)alloc

{

    return [[self currentEnvironment] retain];

}

+ (id)allocWithZone:(NSZone *)zone

{

    return [[self currentEnvironment] retain];

}

- (id)copy

{

    return self;

}

- (id)copyWithZone:(NSZone *)zone;

{

    return self; //确保copy对象也是唯一

}

- (id)retain

{

    return self; //确保计数唯一

}

- (NSUInteger)retainCount

{

    return NSUIntegerMax;  //这样打印出来的计数永远为-1

}

- (oneway void)release

{

    //do nothing

}

+ (void)release

{

    //do nothing

}

- (id)autorelease

{

    return self;//确保计数唯一

}

 

@end

posted on 2016-06-16 17:17  🌞Bob  阅读(106)  评论(0编辑  收藏  举报

导航