自杀:Objective-C 对象调用自己的 -dealloc 方法 [英] Suicide: Objective-C objects calling their own -dealloc methods on themselves

查看:51
本文介绍了自杀:Objective-C 对象调用自己的 -dealloc 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C 中的对象自杀是好习惯吗?也就是说,对于声明 [self dealloc] 的对象,-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?

碰巧我有一个特定的例子,一个自定义计时器对象,它扩展了 NSObject 并包含一个 NSTimer 实例和一个 NSUInteger,它被设置为限制计时器触发的次数.当时间到时,对象告诉计时器 -invalidate 然后通过调用它的 -dealloc 方法自杀.由于这是自动的,因此我们不必担心必须跟踪对象或至关重要地知道何时是解除分配的正确时机.

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.

推荐答案

Objective-C 中的对象自杀是好习惯吗?也就是说,对于一个声明 [self dealloc] 的对象,其中 -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?

没有

您应该编写对 dealloc 的调用的唯一时间是将 dealloc 发送到您的类之一的 dealloc 方法中的超级对象.没有例外.

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.

如果您尝试在任何其他时间将 dealloc 发送到一个对象,则可能会使其他对象带有悬空指针.不要这样做.

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.

你应该向自己发送释放吗?这是另一回事,但您仍应遵循 内存管理规则.如果你已经给self发送了retain,那么在某个时候你需要向self发送release.init 中有一个例外,如果初始化失败,您必须释放 self 并返回 nil(我猜您可以声称 alloc 已将保留发送给 self).

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).

这篇关于自杀:Objective-C 对象调用自己的 -dealloc 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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