Add date to MKAnnotation title property
I'm following the Nerd Ranch i0S Programming guide. I need to tag map annotations with the dates that they were created.
The following method I created overrides the MKAnnotation title property:
- (void)setTitle:(NSString *)t
{
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
// Obtain copy of passed title.
[t retain];
[title release];
// Set required date format.
[date开发者_运维百科Formatter setDateFormat:@"dd-MM-yyyy"];
title = [NSString stringWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]];
}
The app crashes at the last line of this method. Can someone please help?
NSString’s +stringWithFormat
returns an autoreleased object—since nothing else is taking ownership of it, your title
is getting deallocated at the end of the run-loop cycle. You need to call retain
on the new value of title
, like this:
title = [[NSString stringWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]] retain];
or, alternatively, set it to a newly-allocated instance (hence not an autoreleased one), like this:
title = [[NSString alloc] initWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]];
I'm not sure, but would it help if you replaced the line
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
with
[dateFormatter setDateFormat:[NSString stringWithFormat:@"dd-mm-yyyy"]];
精彩评论