适用于iPhone的Objective-C-使用简单日期命令时应用程序崩溃
我仍在学习Objective-C,所以如果这是一个简单的业余错误,请原谅我,但我想我们都必须以某种方式学习 基本上,我有一个应用程序,在屏幕的标题处有一个简单的文本,它已经被iboutleted并称为“headerText”。我想把它改为“2月摘要”,用任何月份替换2月——因此必须动态获取月份适用于iPhone的Objective-C-使用简单日期命令时应用程序崩溃,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,我仍在学习Objective-C,所以如果这是一个简单的业余错误,请原谅我,但我想我们都必须以某种方式学习 基本上,我有一个应用程序,在屏幕的标题处有一个简单的文本,它已经被iboutleted并称为“headerText”。我想把它改为“2月摘要”,用任何月份替换2月——因此必须动态获取月份 - (void)setHeaderText { NSString *headerTextTitle; NSString *monthString; NSDate *mo
- (void)setHeaderText {
NSString *headerTextTitle;
NSString *monthString;
NSDate *month;
NSDateFormatter *dateFormat;
month = [[NSDate alloc] init]; // Automatically fills in today's date
[dateFormat setDateFormat:@"MMMM"];
monthString = [dateFormat stringFromDate:month];
headerTextTitle = [[NSString alloc] initWithFormat:@"Summary for (%@)", monthString];
headerText.text = headerTextTitle;
[headerTextTitle release];
[monthString release];
[month release];
[dateFormat release];
}
很明显,我可以修改文本和内容,但是每当我在viewDidLoad上调用此方法时,我发现应用程序就会崩溃。谁能告诉我怎么了?我认为这是一个错误:
[dateFormat setDateFormat:@"MMMM"];
因为当使用断点时,事情会变得有点滑稽。我做错了什么?我很困惑
我感谢你的帮助
杰克
编辑:我现在正在这样做:
month = [[NSDate alloc] init]; // Automatically fills in today's date
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM"];
monthString = [dateFormat stringFromDate:month];
但它仍然失败?在使用NSDateFormatter之前,您应该分配/初始化它…您的dateFormat一开始是未定义的 你需要初始化它,比如
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
您不应该释放
monthString
,因为它是一个自动释放对象
看
对象所有权
规则#1–如果使用alloc或copy创建对象,则需要释放该对象
规则#2–如果没有直接创建对象,请不要尝试释放对象的内存
解决了这个问题:
NSString *monthString = [[NSString alloc] init];
必须放进去。现在它工作得很好:)谢谢大家 这样做,把它缩短一点怎么样:
- (void) setHeaderText
{
NSDateFormatter* formatter = [NSDateFormatter defaultFormatterBehavior];
[formatter setDateFormat: @"MMMM"];
headerText.text = [NSString stringWithFormat:
@"Summary for (%@)", [dateFormat stringFromDate: [NSDate date]]];
}
这不是正确的答案。epatel的两个答案都是这个代码中的崩溃bug。您要使用的月份字符串是由
[dateFormat stringFromDate:month]提供给您的代码>。没有必要自己分配一个。只要去掉month string上不平衡的版本就行了。你是对的,谢谢你指出这一点。我认为它是正确的,因为它生成了我想要的结果,并且没有崩溃或其他任何事情——感谢您指出:)