问题
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 @synthesize
d 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