I am reading up about Encoding and Decoding and I noticed that sometimes people miss the retain off the end, I have also noticed that retain is sometimes used on some varables but not others. Can I ask …
(1) What is the purpose of this retain and why is it sometimes not needed?
(2) Does the use of the retain imply that I need to match it with a release, and if so where?
- (id) initWithCoder: (NSCoder *) decoder {
name = [[decoder decodeObjectForKey: @"CardName"] retain];
email = [[decoder decodeObjectForKey: @"CardEmail"] retain];
}
or
- (id) initWithCoder: (NSCoder *) decoder {
name = [decoder decodeObjectForKey: @"CardName"];
email = [decoder decodeObjectForKey: @"CardEmail"];
}
gary
Your first snippit represents the correct behaviour. The
-decodeObjectForKey:method does not contain the wordinit,copyornew, so there is no promise made about whether the object returned will stay around, and if so for how long. If your object needs its ivars to stay around, it should-retainthe objects it gets back from the decoder. This-retainwill need to be balanced with a-release, which will be in your object’s-deallocmethod (so the object is created with some initial ivars which it retains, and it releases its ivars when it is destroyed). Like this:The retain/release dance is not needed:
if you’re using garbage collection
if your object doesn’t need to claim ownership of its ivars. That’s not often the case; delegates usually aren’t retained (but then usually aren’t archived either), and properties declared with the
assignmodifier aren’t either.