Please see my comments in code:
-(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t
{
[super init];
coordinate = c;
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSString* formattedDate = [NSString stringWithFormat:@"%@ %@",
[dateFormatter stringFromDate:today], t];
[self setTitle:formattedDate]; //Why does the app crash when I try and release formattedDate? I have after all passed its reference to the title property?
[dateFormatter release]; //I need to release the dateformatter because I have finished using it and I have not passed on a reference to it
return self;
}
Nope, looks fine.
stringWithFormatreturns an autoreleased object – you don’t own it unless youretainit, which you haven’t, so you mustn’t release it. You allocateddateFormatteryourself, so you do own it and mustrelease.(See the object ownership documentation and 8 squillion very similar SO questions. This must be the number one objective-c problem that crops up here by a significant margin.)
Edit: Actually, looking at your comment, there is a very slightly subtler issue here, though the upshot is the same (and actually underlines the point about ownership).
When you pass the string to
setTitle, it couldretainthe string itself, in which case a call toreleasehere might not cause a crash immediately. You would still be over-releasing, however, and it would bite you in the end. It just would be more difficult to locate the cause of the problem further down the line.As it happens,
setTitlemakes a copy rather than retaining yours. This is pretty common withNSStringproperties. One reason is that you might pass anNSMutableStringinstead, and then randomly change it at some later point that might screw up the receiver. Taking a private copy is safer. As a bonus it exposes your over-releasing right away and allows you to fix it easily.In any case, the point stands: only ever
releasesomething you know you own. If you’ve just passed it to some other object, it’s that object’s responsibility to handle whether it owns it or not, not yours.