Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 failing?

like image 815
Jack Avatar asked Dec 12 '25 00:12

Jack


2 Answers

Your dateFormat is undefined for a start.

You need to initialise it, something like

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
like image 71
Abizern Avatar answered Dec 13 '25 16:12

Abizern


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

like image 29
epatel Avatar answered Dec 13 '25 16:12

epatel