0

I am reading a RSS and from there an element: <pubDate>Thu, 07 Apr 2011 13:37:41 +0000</pubDate> I use the following code to turn the received string into NSDate

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];  

        [dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"]; // Thu, 18 Jun 2010 04:48:09 -0700 


        NSDate *date = [dateFormatter dateFromString:[self.currentDate stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];        

        [item setObject:date forKey:@"date"]; 

Code's working perfectly in simulator but on device it crashes. The reason is that NSDate object stays nil and when I'm adding it to the dictionary it crashes the app.

I read a lot around about this problem but none of the solutions worked for me. I mean lots of them did, but in simulator...

Any help appreciated, Luka ...

luigi7up
  • 5,779
  • 2
  • 48
  • 58
  • Could print the orginal date string to the console, this way we can check if the format is correct. The reason why it nil is because the date formatter can't parse the date string. You should check if the date is nil before adding it to the array, just in case. – rckoenes Apr 07 '11 at 11:47

2 Answers2

1

Check two things to eliminate the differences between simulator and ios device.

  1. iOS Device is case sensitive. So you have to check your string if there is something wrong.

  2. Locale setting can be different with your simulator and iOS. to prevent this define proper locale of date formatter.

    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    [dateFormatter setLocale:usLocale];

Alkimake
  • 1,797
  • 14
  • 30
  • It was the problem of setting the local for the date formatter. Could you give me the explanation of what setLocale does? Is it forcing the device to use US local settings instead of spanish ones as in my case? Also, can I expect problems on other devices? Thanks a lot. L – luigi7up Apr 07 '11 at 12:15
  • setLocale simply doing Localization. Date formatter tries to parse "Thu" instead of "Jue" as Thursday when you set locale en_US. – Alkimake Apr 07 '11 at 13:38
0

Test your formatter's behaviour by

[dateFormatter dateFromString:[NSDate date]]

If it's not the formatter's format it means that your nsstring is the one to blame.

Could you log the string that you are trying to convert? It's probably the one at fault

NSLog(@"string is: %@", self.currentDate);
Stefan Ticu
  • 2,093
  • 1
  • 12
  • 21