将日期添加到 MKAnnotation 标题属性

发布于 2024-12-02 05:21:19 字数 551 浏览 6 评论 0原文

我正在遵循 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]];
}

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

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.
    [dateFormatter 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坏尐絯 2024-12-09 05:21:19

NSString 的 +stringWithFormat 返回一个自动释放的对象,因为没有其他东西拥有它的所有权,所以您的 title 在运行循环周期结束时被释放。您需要对 title 的新值调用 retain,如下所示:

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

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

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

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]];
软糯酥胸 2024-12-09 05:21:19

我不确定,但是如果您将线路替换

[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 

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

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"]]; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文