1

In my model object, I'm assigning a date like this:

static NSDateFormatter *dateFormat = nil;
if (nil == dateFormat) {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
}

dateCreated = [dateFormat dateFromString:@"2013-03-04 09:16:41"];

What I'm seeing is that dateFormat is always nil; therefore, dateCreated is set to nil. Not sure how to go about debugging this...

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
davidm
  • 315
  • 3
  • 10
  • why you want dateFormat as static? – Anoop Vaidya Mar 04 '13 at 14:41
  • Here is a good explanation of the `static` keyword: http://stackoverflow.com/a/572550/620197 – Mike D Mar 04 '13 at 14:49
  • I've read about reusing a static formatter ([example](http://stackoverflow.com/questions/4453550/iphone-sdk-best-practice-for-using-nsdateformatter-in-cellforrowatindexpath)). In my case, this NSDateFormatter would be recreated thousands of times, so the goal was to reduce that expenditure. – davidm Mar 04 '13 at 14:51
  • @davidm: This means your design is not good. Why to create a formatter in a method/loop and call it thousands of time. Search for better design. – Anoop Vaidya Mar 04 '13 at 14:52
  • 2
    @AnoopVaidya I don't agree; this is simply a singleton pattern, done locally and there is no reason to suspect the design is incorrect. – trojanfoe Mar 04 '13 at 14:57
  • @davidm, NSDateFormatter is resource heavy thus reusing it is bad practice. – OhadM Aug 03 '15 at 08:36

2 Answers2

10

The issue is simply that you've introduced another non-static dateFormat variable inside the if statement.

Try this:

static NSDateFormatter *dateFormat = nil;
if (nil == dateFormat) {
    dateFormat = [[NSDateFormatter alloc] init]; // NOT NSDateFormatter *dateFormat = ...
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

reason for NSDateFormatter not nill is the static keyword in the start, static keyword initialize the NSDateFormatter nil only once and when you check the NSDateFormatter later in your code, it is never nil

nsgulliver
  • 12,655
  • 23
  • 43
  • 64
  • it initialize the `NSDateFormatter` to nil only once and whenever later on in the app you try to access it, it will never be nil – nsgulliver Mar 04 '13 at 14:45
  • 1
    I still don't understand what you mean. That is not the issue the OP is having anyway; he's simply using 2 variables with the same name at different scopes... – trojanfoe Mar 04 '13 at 14:46
  • i explained what static does in c or objectivc-c but you have clarified in your answer about what is his problem, +1 for your answer – nsgulliver Mar 04 '13 at 14:52