prefixing property instance vars 给实例变量添加前缀

来源:互联网 发布:ubuntu 16 chroot 编辑:程序博客网 时间:2024/06/07 22:53

原文:摘自http://www.cocoabuilder.com/archive/cocoa/198573-property-problem.html

 Not prefixing property instance vars can lead to a type of mistake where, in the implementation of the same class, you accidentally write something like


contents = [NSArray array];


when you meant to write


self.contents = [NSArray array];


Do you see the problem? Assuming no GC, and the 'contents' property is
marked 'retain' or 'copy', the first line will cause a crash sometime
later on, because you directly assigned an autoreleased value to an
instance variable, so sometime after this method leaves scope, that
array is going to be dealloced and 'contents' will be a bad pointer.
The second line invokes the property's setter method, which correctly
retains or copies the array.


实例变量不使用前缀的话有时候会导致一些错误,比如在类的实现文件中,不小心写了如下的一句:

contents = [NSArray array]; //LINE1

而你实际想表达的是

self.contents = [NSArray array];//LINE2

看到问题了吗?假设没有垃圾回收,而contents属性被标记为retain或者copy,第一行有时候会导致程序崩溃,因为你直接把一个自动释放的值赋给了一个实例变量,所以当这个方法离开作用域之后,可能数组会被自动回收,contents属性就变成了一个坏指针。第二行调用属性的setter方法,可以正确地retain或者copy数组(我的理解是retain使数组的引用计数加了1,copy复制了数组)。