问题描述
我有对象:
MyClass *obj= [[MyClass alloc] init];
有什么区别:
[obj release]; // Only obj own this object.
和:
obj = nil;
当我设置obj = nil时,iOS deallocs obj吗?
Does iOS deallocs obj when i set obj = nil?
我有一个指针,有时候我把它指向一个对象,有时则没有。所以,当我想释放指针时,我必须检查它是否为零?
I have a pointer, sometime i set it point to an object, sometime do not. So, when i want release a pointer i must check is it nil?
推荐答案
上一个十年的回答,
现在只有具有历史意义。
今天,你必须使用ARC。
干杯
非常简短的答案是 不要 只需将其设置为零。 您必须将其释放。 将其设置为nil与释放它无关。你必须释放它。
The very short answer is DO NOT just set it to nil. You must release it. Setting it to nil has no connection to releasing it. You must release it.
但是值得记住如果是属性,那么
self.obj = nil;
将在事实中为您发布。当然,你不能忘记自我。部分!!!!
will in a fact release it for you. Of course, you must not forget the "self." part !!!!
确实,
self.obj = anyNewValue;
确实会为你释放旧内存,神奇地清理一切并用新值设置它。所以,self.obj = nil只是一个特殊情况,它释放并清理所有内容,然后将其保留为零。
will indeed release the old memory for you, clean everything up magically and set it up with the new value. So, self.obj = nil is just a special case of that, it releases and cleanses everything and then just leaves it at nil.
所以,如果有人读到这个是新的并且完全被记忆混淆了,
So if anyone reading this is new and completely confused by memory,
-
你必须先释放它,[x release]然后再将它设置为nil x = nil
You must release it, [x release] before setting it to nil x=nil
如果你正在使用一个属性,不要忘记自我。
IF you are using a property, "don't forget the self. thingy"
IF 你正在使用一个属性,你可以说self.x = nil或者确实是self.x = somethingNew它会照顾释放和其他所有复杂的讨厌的东西。
IF you are using a property, you can just say self.x=nil or indeed self.x=somethingNew and it will take care of releasing and all that other complicated annoying stuff.
最后你将不得不学习关于释放,自动释放,等等等等所有复杂的东西。但是生命很短暂,暂时忘掉它: - /
Eventually you will have to learn all the complicated stuff about release, autorelease, blah blah blah. But life is short, forget about it for now :-/
希望它有所帮助。
这篇关于将对象设置为nil与在dealloc中发送释放消息之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!