@propert(retain)做了什么?通过我的测试,它实际上并没有保留我的对象:
id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
propertyWithRetain = obj;
NSLog(@"%d", [obj retainCount]);
// output:
// 1
// 1如何创建真正保留对象的属性?
发布于 2011-06-15 23:47:27
你没有在那里使用你的财产,这就是为什么它没有保留!
试试这个:
id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
self.propertyWithRetain = obj; // Note the self. :)
NSLog(@"%d", [obj retainCount]);使用self.将使用该属性。仅仅使用变量名是不会的。
特别是为@bbum编辑(他在评论中提出了一个非常公平的观点)
不要依赖于使用retainCount -你不知道你的对象还保留了什么,你也不知道其中的一些保留是否实际上是计划的自动释放,所以它通常是一个误导性的数字:)
发布于 2011-06-15 23:49:18
propertyWithRetain = obj;这只是将ivar设置为直接支持该属性。合成@属性时,如果没有声明实例变量,则会自动生成一个实例变量。上面的代码直接使用了ivar。
self.propertyWithRetain = obj;这实际上会通过@synthesized设置器,并增加保留计数。
这也是为什么我们很多人使用@synthesize propertyWithRetain = propertyWithRetain_;来改变iVar的名称。
请注意,即使在这种情况下,调用retainCount也可能会产生严重的误导。尝试使用[NSNumber numberWithInt: 2];或常量字符串。真的,别给retainCount打电话。永远不会。
https://stackoverflow.com/questions/6360499
复制相似问题