iphone: How to mix enum like NSCalendar
I just looked at the code in NSCalendar.h like this:
enum {
NSEraCalendarUnit = kCFCalendarUnitEra,
NSYearCalendarUnit = kCFCalendarUnitYear,
NSMonthCalendarUnit = kCFCalendarUnitMonth,
NSDayCalendarUnit = kCFCalendarUnitDay,
NSHourCalendarUnit = kCFCalendarUnitHour,
NSMinuteCalendarUnit = kCFCalendarUnitMinute,
NSSecondCalendarUnit = kCFCalendarUnitSecond,
NSWeekCalendarUnit = kCFCalendarUnitWeek,
NSWeekdayCalendarUnit = kCFCalendarUnitWeekday,
NSWeekdayOrdinalCalendarUnit = kCFCalendarUnitWeekdayOrdinal,
};
typedef NSUInteger NSCalendarUnit;
And in client code, I can call something like:
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags
fromDate:self
toDate:[NSDate date]
options:0];
I don't really get the way this code works.
How can they define an anonymous enum and then define the type of NSCalendarUnit to be NSUInteger. And how can they link between the NSCalendarUnit and the anonymous enum.
And in client code, I can do OR operation
with NSUInteger, then how they (the NSCalendar) parse it out to know what kinds of elements I need to give it back to me?
They're pulled out using the &
operator. This is called a bitfield, and Wikipedia has an OK article on how they work: http://en.wikipedia.org/wiki/Bit_field
I also answered a question recently on how bitwise operators work: https://stackoverflow.com/questions/3427585#3427633
链接地址: http://www.djcxy.com/p/72660.html上一篇: 一元运营商如何工作?