zoukankan      html  css  js  c++  java
  • 单例-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

  • 相关阅读:
    软件测试人员的要求
    冒烟测试和回归测试的区别
    [go]struct
    [go]socket编程
    [go]gorhill/cronexpr用go实现crontab
    [go]os/exec执行shell命令
    [go]time包
    [go]etcd使用
    [go]redis基本使用
    [go]go操作mysql
  • 原文地址:https://www.cnblogs.com/isItOk/p/5591643.html
Copyright © 2011-2022 走看看