What does @property(retain) do?

最后都变了- 提交于 2019-12-25 14:48:31

问题


What does @propert(retain) do? it doesn't actually retain my object by my tests:

id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
propertyWithRetain = obj;
NSLog(@"%d", [obj retainCount]);

// output:
// 1
// 1

How can I make a property that will really retain the object?


回答1:


You're not using your property there, that's why it's not retaining!

Try this :

id obj = getObjectSomehow();
NSLog(@"%d", [obj retainCount]);
self.propertyWithRetain = obj; // Note the self. :)
NSLog(@"%d", [obj retainCount]);

Using self. will use the property. Just using the variable name won't.


EDIT especially for @bbum (who raises a very fair point in the comments)

Don't rely on using retainCount - you don't know what else has retained your object and you don't know if some of those retains are actually scheduled autoreleases so it's usually a misleading number :)




回答2:


propertyWithRetain = obj;

That just sets the ivar backing the property directly. When an @property is synthesized, if there is no instance variable declared, then one is generated automatically. The above is using that ivar directly.

self.propertyWithRetain = obj;

That would actually go through the @synthesized setter and bump the retain count.

Which is also why many of us use @synthesize propertyWithRetain = propertyWithRetain_; to cause the iVar to be named differently.

Note that, even in this, calling retainCount can be horribly misleading. Try it with [NSNumber numberWithInt: 2]; or a constant string. Really, don't call retainCount. Not ever.



来源:https://stackoverflow.com/questions/6360499/what-does-propertyretain-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!