自杀:Objective-C 对象调用自己的 -dealloc 方法
Objective-C 中的对象自杀是个好习惯吗?也就是说,对于声明 [self dealloc]
的对象,其中 -dealloc
允许像往常一样有序结束?主要风险有哪些?
碰巧我有一个具体的例子,一个自定义计时器对象,它扩展了 NSObject 并包含一个 NSTimer 实例和一个 NSUInteger,它被设置为限制计时器触发的次数。当时间到时,对象告诉计时器-invalidate
,然后通过调用其-dealloc
方法自杀。由于这是自动的,我们不必担心必须跟踪对象或关键地知道何时是释放它的正确时机。
有关更详细的说明,请参阅我在此处的帖子。
Is it good practice for an object in Objective-C to commit suicide? That is, for an object to declare [self dealloc]
where -dealloc
permits an orderly wind down as usual? What are the principal risks?
As it happens I have a specific example, a custom timer object that extends NSObject and comprises an NSTimer instance and an NSUInteger which is set to limit the number of times the timer fires. When time is up the object tells the timer to -invalidate
and then commits suicide by calling its -dealloc
method. As this is automatic we have no worries about having to track the object or crucially knowing when is the correct moment to deallocate it.
For a more detailed explanation see my post over here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该调用 -dealloc。相反,调用 [self release] 使引用计数变为 0,并让系统调用 -dealloc。
You shouldn't be calling -dealloc. Instead call [self release] so the reference count goes to 0 and let the system call -dealloc.
不。
您应该编写对 dealloc 的调用的唯一一次是将 dealloc 发送到某个类的 dealloc 方法中的超级对象。没有例外。
如果您尝试在任何其他时间向对象发送 dealloc,则可能会导致其他对象留下悬空指针。不要这样做。
你应该向自己发送释放吗?这是另一回事,但您仍然应该遵循 内存管理规则。如果您已将retain发送给self,那么在某些时候您将需要将release发送给self。 init 中有一个例外,如果初始化失败,你必须释放 self 并返回 nil (我猜你可以声称 alloc 已将保留发送给 self)。
No.
The only time you should ever write a call to dealloc is to send dealloc to the super object in the dealloc method of one of your classes. No exceptions.
If you try to send dealloc to an object at any other time, you risk leaving other objects with dangling pointers. Don't do it.
Should you ever send release to self? That is a different matter, but you should still follow the Memory Management Rules. If you have sent retain to self, then at some point you will need to send release to self. There is one exception which is in init, if initialisation fails you have to release self and return nil (I guess you could claim that alloc has sent retain to self).