Search code examples
objective-cnullnsdatenscalendar

(OBJ C) Sending message calendarIdentifier to an instance of NSCalendar and receiving null


I am trying to send the message calendarIdentifier to an instance of an NSCalendar. This is my code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {

//Create a date instance.
NSDate *now = [NSDate date];
NSLog(@"This NSDate Object lives at %p", now);
NSLog(@"The date now is %@",now);

//Seconds from the date instance and 1970.
NSTimeInterval seconds_since_1970 = [now timeIntervalSince1970];
NSLog(@"Seconds since 1970: %f", seconds_since_1970);

//Future date from date instance.
NSDate *later = [now dateByAddingTimeInterval:100000];
NSLog(@"The date after 100,000 seconds from %@ is : %@", now, later);

//Create calender instance with user settings.
NSCalendar *cal = [[NSCalendar alloc] init];
NSString *calenderIdentity = [cal calendarIdentifier];
NSLog(@"My calender is %@", calenderIdentity);



return 0;
}

However, for some reason I get this as a return in the console:

2015-01-08 19:12:26.651 TimeAfterTime[1325:40863] This NSDate Object lives at 0x10010fe70
2015-01-08 19:12:26.656 TimeAfterTime[1325:40863] The date now is 2015-01-09 00:12:26 +0000
2015-01-08 19:12:26.656 TimeAfterTime[1325:40863] Seconds since 1970: 1420762346.651615
2015-01-08 19:12:26.656 TimeAfterTime[1325:40863] The date after 100,000 seconds
from 2015-01-09 00:12:26 +0000 is : 2015-01-10 03:59:06 +0000
2015-01-08 19:12:26.656 TimeAfterTime[1325:40863] My calender is (null)
Program ended with exit code: 0

Why am I getting null? I tried looking around but can't seem to find anything.

Thanks,


Solution

  • You need to supply a known calendar type to the initWithCalendarIdentifier: initializer. Just providing any string doesn't work. The known types are:

    NSGregorianCalendar
    NSBuddhistCalendar
    NSChineseCalendar
    NSHebrewCalendar
    NSIslamicCalendar
    NSIslamicCivilCalendar
    NSJapaneseCalendar
    NSRepublicOfChinaCalendar
    NSPersianCalendar
    NSIndianCalendar
    NSISO8601Calendar
    

    This will produce a non-null value for the identifier: message.

    I found these constants in NSLocale.h.