Objective C iPhone何时将对象引用设置为nil [英] Objective C iPhone when to set object references to nil
问题描述
我已经用目标C和Cocoa框架开发了很长一段时间了。然而,我仍然不是绝对清楚,我什么时候应该将对象引用设置为nil。我知道建议在释放具有委托的对象之前这样做,并且您还应该在viewDidUnload方法中对保留的子视图执行此操作。但究竟何时应该这样做,为什么?它究竟完成了什么?提前谢谢你。
I have been developing with objective C and the Cocoa framework for quite some time now. However it is still not absolutely clear to me, when am I supposed to set object references to nil. I know it is recommended to do so right before releasing an object that has a delegate and you should also do so in the viewDidUnload method for retained subviews. But exactly when should this be done and why?. What does it accomplish exactly?. Thank you in advance.
-Oscar
推荐答案
说你有在类'界面中定义的指针 myView
:
Say you have a pointer myView
defined in your class' interface:
@interface MyClass {
UIView *myView;
}
@end
然后在你的代码中,某些时候,你可以释放那个变量:
Then in your code, at some point, you may release that variable:
[myView release];
执行此操作后, myView
,指针,不会指向nil,而是指向一个可能不再存在的对象的内存地址(因为你刚刚发布它)。所以,如果你碰巧在此之后做了一些事情,比如:
After you do that, myView
, the pointer, won't be pointing to nil, but will be pointing to a memory address of an object that may not exist anymore (since you just released it). So, if you happen to do something after this, like:
[myView addSubview:otherView];
你会收到错误。
另一方面,如果你这样做:
If, on the other hand, you do this:
[myView release];
myView = nil;
...
[myView addSubview:otherView];
对 addSubview
的调用将不会有任何负面影响,因为忽略消息为零。
the call to addSubview
will not have any negative impact, since messages to nil are ignored.
作为推论,您可能会看到使用 retain <的建议/ code>属性,例如:
As a corollary, you may see suggestions of using retain
properties, such as:
@property(retain) UIView *myView;
然后在代码中执行:
self.myView = nil;
通过这样做,合成访问器将释放旧对象并将引用设置为一行中的nil代码如果你想确保你的所有属性都被释放并设置为nil,这可能会很有用。
By doing that, the synthesized accessor will release the old object and set the reference to nil in one line of code. This may prove useful if you want to make sure all your properties are both released and set to nil.
你必须永远忘记的一点是,内存管理已经完成通过保留
发布
来电,而不是通过分配nil。如果你有一个保留计数为1的对象,并将nil分配给它的唯一变量,你就会泄漏内存:
One thing that you must never forget, is that memory management is done by means of retain
release
calls, and not by means of assigning nil. If you have an object with a retain count of 1, and assign nil to it's sole variable, you'll be leaking memory:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,10,10)];
view = nil;
// You just leaked a UIView instance!!!
这篇关于Objective C iPhone何时将对象引用设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!