I\'m going through all of my documentation regarding memory management and I\'m a bit confused about something.
When you use @property, it creates getters/setters for th
When you create a retain
setter, you're creating something like this:
- (void)setString:(NSString *)someString {
if (someString != string) {
[string release];
[someString retain];
string = someString;
}
}
If you don't use the setter, the new value is not getting that retain—you don't "own" that string, and because it's all references, if the original string is released, you might be facing a null reference, which will lead to an EXC_BAD_ACCESS
. Using the setter ensures that your class now has a copy of that value—so yes, it does increment the retain count of the new value. (Note that using the getter is a convention of OOP—that outsiders should not be able to directly touch the ivar. Also in your getter you can modify the value, maybe returning an NSArray when your ivar is an NSMutableArray, for example).
You shouldn't autorelease
in a setter—Apple has used it in their sample code, but a thing to keep in mind is that setters are called a lot—millions of times, potentially. All of those objects are going into the same autorelease pool, so unless you create your own and/or regularly flush it, you'll have a ton of elements in your pool, all unneeded but still taking up RAM. Much better to simply release
.
As for dealloc, trace back through that setter. If you send a release
directly, it's obvious—you release that object. But if you write self.string = nil;
, what you're doing is this:
if
blockretain
nil: messages to nil do nothing, and you don't crashAs a matter of convention, I use release
in my dealloc
method, because release
seems more final, and dealloc
is the final method call your object will receive. I use self.string = nil;
in viewDidUnload and the memory warning methods.
Hope this helps!