zoukankan      html  css  js  c++  java
  • 不要在初始化方法和dealloc方法中使用Accessor Methods

    苹果在《Advanced Memory Management Programming Guide》指出:

    Don’t Use Accessor Methods in Initializer Methods and dealloc The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:

    - init {
        self = [super init];
        if (self) {
            _count = [[NSNumber alloc] initWithInteger:0];
        }
        return self;
    }
    

    唯一不需要使用Accessor Methods的地方是initializer和dealloc. 在苹果官方文档中没有解释为什么。经过一番查阅后,最主要的原因是此时对象的状况不确定,尚未完全初始化完毕,而导致一些问题的发生。

    例如这个类或者子类重写了setMethod,里面调用了其他一些数据或方法,而这些数据和方法需要一个已经完全初始化好的对象。而在init中,对象的状态是不确定的。

    举个例子,一个子类重写了set方法,在里面进行了一些子类特有的操作,而此时如果父类在init直接使用Accessor Methods,就会导致问题的发送。

    其它一些问题还有,像会触发KVO notification等。

    总之,记住在开发中记住这个principle最重要。

    在开发中,我发现还是有人因为疏忽或不知道而直接在init方法里面使用self.property = XXX来进行赋值,留下了一些隐患。

  • 相关阅读:
    mybatis-plus
    AOP中Cache操作实现
    ab和webbench的安装以及使用
    git commit的提交规范
    CGI、FastCGI、PHP-CGI与PHP-FPM的概念以及各个之间的关系
    PHP垃圾回收机制(GC)
    PhpStorm中php文件如何在console中运行
    ELK-logstash导入数据以及配合kibana使用
    领扣刷题——关于数
    Uncaught SyntaxError: Illegal return statement
  • 原文地址:https://www.cnblogs.com/songxing10000/p/4822314.html
Copyright © 2011-2022 走看看