I’m working through Aaron Hillegass’ book, specifically the lottery example. I had a question about the -setEntryDate: method; why do I have to retain date? The program still works without retaining it.
-(void)setEntryDate:(NSCalendarDate *)date {
[date retain];
[entryDate release];
entryDate = date;
}
But this still works fine:
-(void)setEntryDate:(NSCalendarDate *)date {
entryDate = date;
}
So why is it correct that I have to retain date and then release entryDate?
It works for now, but if you were writing a larger program there is a possibility that, at some indeterminable point in the future, the object
datepoints to would be released by whomever calledsetEntryDate. If that happened, it would be invalidated throughout the rest of the program. You are retaining this object in the class because that class now owns a reference to that object and needs to indicate that. By doing this, even if whatever class calledsetEntryDatewere to releasedate, your class would still maintain a valid reference to it. Also, this is not just a regular old method you are writing. This is a setter, which has the specific responsibility of setting an instance variable on the class it belongs to. If you were writing a non-setter method, you may not have to retain the parameters. What I’m trying to say is that retaining method parameters is not always necessary; it just is in this case (and pretty much with all setters that deal with non-primitive types).This is called “reference counting” and is explained in great detail here. For now, since you are just starting to learn, don’t worry about reading that yet. When you start to get into more complex scenarios with memory management, then that guide is a very valuable piece of reading.