问题描述
我有一个简单的查询,我想由某人清除...是不是保留自己的做法?
我有一个服务器请求对象我想做的。我想要能够以下面的方式使用它:
ARequest * request = [ARequest request:someParam];
request.delegate = self;
[request begin];
为了使对象不会在自动释放池耗尽后自毁,需要在它的init方法中调用retain,然后一旦服务器响应被接收,处理并传递给它的代理就发布。
但是,钟在我的头用这种方法。更好的方法?
保留 self没有错误
,只要你按照正常的内存管理协议在一些明确定义的点释放它。如果一个对象要求自己存在,直到满足某些条件,它应该承担责任,以同样的方式,它需要继续存在的任何其他对象。
(在垃圾回收方法中的等价方法是,在对象的所有者上,收集的代码将使对象在结果待处理时将其自身从垃圾回收中排除,或者如果您不喜欢这个想法,则通过某种类型的集合将它自己根除。)
I have a simple query that I'd like cleared up by someone... Is it bad-practice to retain self?
I have a server request object that I'd like to make. I'd like to be able to use it in the following fashion:
ARequest *request = [ARequest request: someParam];
request.delegate = self;
[request begin];
In order for the object not to self destruct as soon as the autorelease pool is drained, I imagine I need to call a retain in it's init method and then a release once the server response has been received, processed and delivered to it's delegate.
However, something is raising a warning bell in my head with this approach. Better ways to do it?
There is nothing wrong with retaining self
, as long as you release it at some well-defined point in accordance with normal memory management protocol. If an object requires itself to exist until some condition is met, it should take responsibility for that, in the same way as it does for any other object it requires to continue existing.
Introducing otherwise extraneous manager objects or foisting the responsibility off on the object’s owner for superstitious reasons would be the real anti-pattern here.
(The equivalent approach in garbage-collected code would be for the object to exclude itself from garbage collection while results are pending, or root it through a collection of some sort if you dislike that idea.)
这篇关于糟糕的做法,保留“自我”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!