Objective-C for iPhone - 使用简单日期命令时应用程序崩溃

3

我还在学习Objective-C,如果这是一个简单的业余错误,请原谅我,但我想我们都必须以某种方式学习。

基本上,我有一个应用程序,其中包含一小段简单的文本,位于屏幕的标题处,已经使用IBOutlet命名为'headerText'。我希望它显示“二月摘要”,用当前月份替换二月 - 因此必须动态获取月份。

   - (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];

但是它仍然失败了吗?
5个回答

3

首先,您的dateFormat未定义。

您需要初始化它,例如:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

1

这样做可以让它变得更短一些:

- (void) setHeaderText
{
    NSDateFormatter* formatter = [NSDateFormatter defaultFormatterBehavior];
    [formatter setDateFormat: @"MMMM"];
    headerText.text = [NSString stringWithFormat:
        @"Summary for (%@)", [dateFormat stringFromDate: [NSDate date]]];
}

1

在使用NSDateFormatter之前,您应该进行alloc/init操作...


1

你不应该释放monthString,因为它是一个自动释放的对象。

请参考this

对象所有权

规则#1-如果使用alloc或copy创建了一个对象,则需要释放该对象。

规则#2-如果您没有直接创建对象,请勿尝试释放对象的内存。


0
解决了:
NSString *monthString = [[NSString alloc] init];

必须加入。现在它运行良好 :) 谢谢大家!


1
这不是正确的答案。epatel的两个答案都是这段代码中的崩溃错误。你想要使用的月份字符串是由[dateFormat stringFromDate:month];给出的。没有必要自己分配一个。只需消除月份字符串上未平衡的释放即可。 - Ken
你说得对,谢谢指出。我以为它是正确的,因为它生成了我想要的结果,并且没有崩溃或其他问题 - 谢谢你指出来 :) - Jack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接