Objective-C中的[自我释放]是什么意思?
Possible Duplicate:
Is calling [self release] allowed to control object lifetime?
What will happen if I use this code snippet?
[self release]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
self
将其自己的保留计数减一,就像release
对任何其他对象所做的那样。然而,到目前为止,我遇到的唯一情况,这样的调用是合适的,是
init…
的情况方法将失败并预计返回 nil 并取消分配刚刚分配的实例。我估计,十分之九的情况你不应该使用
[self release]
。像这样的东西(基本上禁止调用
- (id)init;
,如果您想强制使用特定的- (id)initWith...
方法.):或 this(基本上强制在初始化时证明对象)
然而,这些并不是
[self release]
合适的唯一场合。但仅限于我迄今为止遇到的那些。 (正如 Oliver 正确指出的那样)编辑:自我无效的
NSTimer
可能是另一种(很常见,但有些特殊)的情况。self
descrements its own retain count by one, just likerelease
would do with any other object.The only situation however that I have so far come across, where such a call was appropriate, was the case where an
init…
method would fail and be expected to return nil and deallocate the just allocated instance.In 9 out of 10 situations you shouldn't use
[self release]
, I'd estimate.Something like this (which basically forbids the calling of
- (id)init;
, for cases where you want to force the use of a particular- (id)initWith…
method.):or this (which basically enforces the proving of an object on initialization)
These however are not the only ever occasions where
[self release]
would be appropriate. But merely the ones I've come across so far. (as Oliver correctly pointed out)Edit: Self-invalidating
NSTimer
s would probably be another (quite common, yet somewhat special) situation.你将释放自己,这意味着该对象声明自己不必仍然存在。如果没有其他人保留该对象,它就会死亡并释放其内存
你没有什么理由这样做,除非如果你想创建不受任何人控制的对象其他都是自我控制的。
我的意思是,例如,在这种情况下,您可能想要创建一个自活对象来进行一些治疗,并在完成后自杀,而不必告诉其他任何人它已经完成。
让我们想象一下,例如一个类,其目的只是向服务器发送消息:
您实例化该类,一旦实例化,它就会向服务器发送一条消息,它等待服务器答复,如果答复正常,它自杀了。这样,您就不必从另一个类控制器中管理任何服务器应答,该类控制器的目的不是管理此类事件。
You will release yourself, what means that the object declares itself that it does not have to still live. If no one else retains tha object, it dies and its memory is freed
You have little reasons to do that, except if you want to create object that are not controlled by anyone else and are self controlled.
I mean, for example, there is the case where you may want to create an self living object that makes some treatments, and suicide when it has finished without having to tell anyone else it has finished.
Let's imagine for example a class whose purpose is just to send a message to a server :
You instanciate the class, as soon as it is istanciated it send a message to a server, it waits for the server answer, and if the answer is ok, it suicide. That way, you don't have to manage any server answer from within another class controller whose purpose is not to manage such events.
它只是减少接收者的引用计数。
It just decrements the receiver’s reference count.