在dealloc中使用setter/mutators [英] Using setters / mutators in dealloc

查看:48
本文介绍了在dealloc中使用setter/mutators的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我正在谈论编写这样的dealloc:

To be specific, I'm talking about writing a dealloc like so:

-(void)dealloc 
{
    self.myvar = nil;
    [super dealloc];
}

我了解这与苹果的建议背道而驰.我也明白,使用在部分解除分配的对象上的设置器,它也可能导致KVO发出.但是,如果我按此顺序进行调用(即:首先是setter,然后是[super dealloc]),这样做是否有任何风险?我试图确切地了解危险是什么,尤其是为什么这是一件不好的事情(tm).谢谢....

I understand this goes against Apple's recommendations. I also understand that it can cause issued with KVO as well using the setter on a partially deallocated object. But if I'm making the calls in this order (ie: setters first, then the [super dealloc]) is there any risk in doing this? I'm trying to understand exactly what the dangers are, and specifically why this is a Bad Thing(tm). Thanks....

推荐答案

除了陈述的原因(可能意味着UB或灾难)之外,您最终可能会遇到对象自身重构以及不自然的依赖周期(例如,子类之间覆盖访问者)-子类可能已经建立了自己的依赖关系,尽管(有效)子类的ivar超出了范围,并且超类不应该知道.它会严重限制对象对子类的可用性,并破坏其实现(因为其实现可能会受到黑客攻击,或者可能会经历某种形式的复活).这就是您要避免的所有内容,出于类似原因,您应该避免init中的访问器.在大型系统中,它变得很丑陋,并且难以维护-同时很容易避免该问题.

in addition to the reasons stated (which can mean UB or disaster), you may end up with objects reconstructing themselves, and unnatural dependency cycles (e.g. among subclasses that override accessors) - the subclasses may have established their own dependencies, although the subclass' ivars are (effectively) out of reach and should not be known to the superclass. it can severely restrict the usability of your objects for subclasses, and break their implementation (because their implementation may expect hacks, or may go through some form of resurrection). this is all stuff you want to avoid, and you should avoid accessors in init… for similar reasons. it gets ugly in large systems, and difficult to maintain - while the issue is easily avoided.

这篇关于在dealloc中使用setter/mutators的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆