释放Vs nil - 最佳实践 [英] release Vs nil -- Best Practice
问题描述
当我们将内存分配给一个类变量时,是否应该在dealloc方法中释放它或将其设置为nil?最佳做法是什么?
最佳做法:
[foo release]; //确保内存被释放
foo = nil; //确保没有指向释放内存的悬挂
其他注意:
分配给声明保留的属性时,
// in your .h
@property(retain)MyObject * foo;
// in your .m
self.foo = bar; // bar is retained;不管以前指的是什么foo被释放
它会释放它以前指向并保留新对象正在分配。
因此,您可以使用:
self.foo = nil ;
它会释放foo指向的任何东西。 但是,如果您的媒体资源未声明为具有保留存储语义,则不会隐式释放foo指向的内容。此外,正如Ryan指出的,一个属性可以被覆盖以产生副作用。因此,最好遵循始终使用的模式:
[foo release];
为了确保没有指向释放内存的悬空指针,您可以:
foo = nil;
如果您不使用具有保留语义的属性,则需要无论存储在变量中:
[foo release];
EDIT:请参阅解释此问题的另一个问题的以下答案:
iPhone - dealloc - Release vs. nil
When we assign memory to a class variable, should we release it or set it to nil in dealloc method? What is the best practice?
解决方案Best practice:
[foo release]; // ensures that memory is released foo = nil; // ensures that there is no dangling pointer to released memory
Other notes:
When you assign to a property declared to retain,
// in your .h @property (retain) MyObject *foo; // in your .m self.foo = bar; // bar is retained; whatever foo previously pointed at is released
it will release what it was previously pointing at and retain the new object being assigned.
So, you can use:
self.foo = nil;
and it will release whatever foo was pointing at. However, if your property was not declared to have retain storage semantics, this will not implicitly release whatever foo was pointing at. Also, as Ryan pointed out, a property can be overridden to have side effects. For this reason, it is best to follow the pattern of always using:
[foo release];
To ensure that you don't have a dangling pointer to released memory, you can follow this up with:
foo = nil;
If you are not using properties with retain semantics, you need to release whatever was stored in the variable:
[foo release];
EDIT: Also see the following answer to another question that explains this:
iPhone - dealloc - Release vs. nil
这篇关于释放Vs nil - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!