将日期添加到MKAnnotation标题属性

时间:2011-08-30 23:11:59

标签: iphone objective-c xcode4 mkannotation

我正在关注Nerd Ranch i0S编程指南。我需要用它们创建的日期来标记地图注释。

我创建的以下方法会覆盖MKAnnotation标题属性:

- (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.
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];

    title = [NSString stringWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]];
}

该应用程序在此方法的最后一行崩溃。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

NSString的+stringWithFormat返回一个自动释放的对象 - 因为没有别的东西取得它的所有权,你的title在运行循环周期结束时被解除分配。您需要在retain的新值上调用title,如下所示:

title = [[NSString stringWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]] retain];

或者,将它设置为新分配的实例(因此不是自动释放的实例),如下所示:

title = [[NSString alloc] initWithFormat:@"%@ %@", t, [dateFormatter stringFromDate:today]];

答案 1 :(得分:-1)

我不确定,但是如果你更换了这行

会有所帮助
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 

[dateFormatter setDateFormat:[NSString stringWithFormat:@"dd-mm-yyyy"]];