Why use "unsigned long" for day of the month?


#1

This seems super basic, but I’m just curious why the book uses the “unsigned long” type for assigning the day of the month in this chapter.

Wouldn’t you want to use an unsigned short since the day of the month will never be more than 31? I struggle with knowing when to use which type so I’m wondering if there is some reason to use unsigned long here that I don’t know about or if it was simply an oversight.

unsigned long day = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forData:now];
NSLog(@"This is day %lu of the month", day);

vs.

unsigned short day = [cal ordinalityOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forData:now];
NSLog(@"This is day %hu of the month", day);

#2

From NSCalendar class reference:

- (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date

According to NSCalendar class reference, NSUInteger (aka unsigned long) is the type of the value returned by the method – ordinalityOfUnit:inUnit:forDate:.

That’s why unsigned long, not unsigned short, should be used.

Don’t struggle: Always stick with what the class API says (Make it a habit.)

[Accelerate your learning and become a competent programmer: pretty-function.org]


#3

Ahh, that makes perfect sense. I wasn’t connecting the dots on NSUInteger and “unsigned long”.

Thanks!


#4

Yes, thanks once again for explaining that.

Just on a separate note here, is there any reason why NSUInteger hasn’t been used here, other than the fact that we haven’t been introduced to these NS types in full yet?