开发者

Objective-C for iPhone - app crashing when using simple date commands

I'm still learning Objective-C so forgive me if this is a simple amateur mistake, but I guess we all have to learn somehow.

Basically I have an app with a simple bit of text, at the header of the screen, which has been IBOutletted and called 'headerText'. I want this to read "Summary for February", replacing February with whatever month it is - so the month must be fetched dynamically.

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

I can obviously modify the text and stuff, but I find the app crashes whenever I call this method on viewDidLoad. Could anyone tell me what's wrong? I THINK it errors in this line here:

[dateFormat setDateFormat:@"MMMM"];

Because when using breakpoints stuff goes a bit funny there. What am I doing wrong? I'm rather confused.

I appreciate the help!

Jack

EDIT: I'm now doing this:

month = [[NSDate alloc] init]; // Automatically fills in today's date
    dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM"];
    monthString = [dateFormat stringFromDate:month];

But it's still fail开发者_如何学编程ing?


Your dateFormat is undefined for a start.

You need to initialise it, something like

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


You should alloc/init an NSDateFormatter before using it...


You shouldn't release monthString as it is an autorelease object.

See this

Object Ownership

Rule #1 – If you create an object using alloc or copy, you need to free that object.

Rule #2 – If you didn’t create an object directly, don’t attempt to release the memory for the object.


How about making it a little shorter by doing something like this:

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


Worked it out:

NSString *monthString = [[NSString alloc] init];

Had to be put in. Now it works fine :) Thanks everyone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜