NSManagedObject init/dealloc 等效项
我在 NSManagedObject 子类 bar
中有一个对象 ivar foo
,只要该对象存在,我就需要始终在那里。
为了确保正确创建 foo
,我对 awakeFromInsert 进行了子类化,以便在创建 bar
时创建 foo
。我在 awakeFromFetch 中做了同样的事情,以确保从存储中获取 bar
时 foo
存在。
为了解决这个问题,我在 willTurnIntoFault 和prepareForDeletion 中释放了foo
。
然而,事实证明,当我删除 bar
时,prepareForDeletion 和 willTurnIntoFault 都会被调用,释放 foo
两次。
我意识到我可能不能在prepareForDeletion中释放它,但我想知道这里的最佳实践是什么,所以我理解什么时候会变成错误,等等。对于一个普通的对象,我只需创建init 中的 foo
并在 dealloc 中销毁它。
谢谢!
I have an object ivar foo
inside a NSManagedObject subclass bar
that I need to be there at all times, as long as the object exists.
To make sure foo
is created properly, I've subclassed awakeFromInsert to create foo
when bar
is created. I've done the same in awakeFromFetch, to make sure foo
is there when bar
is fetched from the store.
To counteract that, I release foo
inside willTurnIntoFault and in prepareForDeletion.
However, it turns out that when I do delete bar
, both prepareForDeletion and then willTurnIntoFault are called, releasing foo
twice.
I realize I can probably just not release it in prepareForDeletion then, but I'd like to know what the best practice is here, so I understand when something gets turned into a fault, etc. For a normal object, I'd just create foo
in init and destroy it in dealloc.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要仅仅释放 ivar,而是释放它并将其设置为 nil。释放
nil
没有任何效果,因此即使发生两次也没关系。更好的是,使
foo
成为具有retain
语义的属性,并始终通过-setFoo:
设置它。Instead of just releasing the ivar, release it and set it to
nil
. Releasingnil
has no effect, so you'll be OK if it happens twice.Better yet, make
foo
a property withretain
semantics and always set it via-setFoo:
.