美文网首页
Custom setter and getter

Custom setter and getter

作者: AprSnow | 来源:发表于2017-02-03 14:55 被阅读8次

    简单的是最容易忽略的。

    不是最好,但你必须理解的写法

    @property (nonatomic, retain) UILabel *someLabel;
    
    -(UILabel *)someLabel
    {
        return _someLabel;
    }
    
    - (void)setSomeLabel:(UILabel *)someLabel
    {
        if (someLabel != _someLabel) {
            [_someLabel release];
            _someLabel = [someLabel retain];
        }
    }
    

    如果你自定义了setter,推荐使用release释放对象

    可能引起crash:

    - (void)delloc
    {
        self.someLabel = nil;
        [super delloc];
    }
    

    推荐:

    - (void)delloc
    {
        [_someLabel release];
        _someLabel = nil; 
        [super delloc];
    }
    

    在Apple官方文档中并不推荐在init和delloc中用Accessor方法,原因Apple也没有解释。

    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.

    stackoverflow中有人提到self.variable = nil可以避免悬挂指针引起的crash,但是如果setter是自定义的,那么[variable release]是更合适的选择。

    Typically, you would either use self.variable = nil which has the benefit that it also sets the variable to nil (avoiding crashes due to dangling pointers), or [variable release] which is the fastest and may be more appropriate in a dealloc method if your setter has custom logic.

    参考

    相关文章

      网友评论

          本文标题:Custom setter and getter

          本文链接:https://www.haomeiwen.com/subject/wnsdittx.html