将日期添加到 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]];
}
应用程序在此方法的最后一行崩溃。有人可以帮忙吗?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString 的
+stringWithFormat
返回一个自动释放的对象,因为没有其他东西拥有它的所有权,所以您的title
在运行循环周期结束时被释放。您需要对title
的新值调用retain
,如下所示:或者,将其设置为新分配的实例(因此不是自动释放的实例),例如这:
NSString’s
+stringWithFormat
returns an autoreleased object—since nothing else is taking ownership of it, yourtitle
is getting deallocated at the end of the run-loop cycle. You need to callretain
on the new value oftitle
, like this:or, alternatively, set it to a newly-allocated instance (hence not an autoreleased one), like this:
我不确定,但是如果您将线路替换
为
I'm not sure, but would it help if you replaced the line
with