是否允许调用[self release]来控制对象的生命周期? [英] Is calling [self release] allowed to control object lifetime?
问题描述
我想在Objective C中创建一个对象,但我没有对它进行引用。
I want to create an object in Objective C but I don't hold a reference to it.
是否可以通过调用[self release]让对象控制自己的生命周期?
Is it allowed to let the object control its own lifetime by calling [self release]?
以防万一你想知道为什么我需要这个:我想创建一个订阅某些通知的对象,但过了一段时间后不再需要该对象并且应该消失。
In case you're wondering why I need this: I want to create an object that subscribes to some notifications, but after a while the object is no longer needed and should go away.
那么,允许以下内容吗?
So, is the following allowed?
- (void) destroyMyself {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self release];
}
推荐答案
规则很简单。如果您拥有对象,则应该只释放它。即,使用以new或alloc开头的方法或包含副本的方法获取对象。
The rules are simple. You should only release an object if you own it. i.e. the object was obtained with a method starting "new" or "alloc" or a method containing copy.
因此,除非之前完成[自我保留],否则对象不得进行[自我释放]或[自动释放]。
An object must not therefore do [self release] or [self autorelease] unless it has previously done [self retain].
这篇关于是否允许调用[self release]来控制对象的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!