iphone:如何像 NSCalendar 一样混合枚举
我只是查看了 NSCalendar.h 中的代码,如下所示:
enum {
NSEraCalendarUnit = kCFCalendarUnitEra,
NSYearCalendarUnit = kCFCalendarUnitYear,
NSMonthCalendarUnit = kCFCalendarUnitMonth,
NSDayCalendarUnit = kCFCalendarUnitDay,
NSHourCalendarUnit = kCFCalendarUnitHour,
NSMinuteCalendarUnit = kCFCalendarUnitMinute,
NSSecondCalendarUnit = kCFCalendarUnitSecond,
NSWeekCalendarUnit = kCFCalendarUnitWeek,
NSWeekdayCalendarUnit = kCFCalendarUnitWeekday,
NSWeekdayOrdinalCalendarUnit = kCFCalendarUnitWeekdayOrdinal,
};
typedef NSUInteger NSCalendarUnit;
在客户端代码中,我可以这样调用:
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags
fromDate:self
toDate:[NSDate date]
options:0];
我真的不明白这段代码的工作方式。
他们如何定义一个匿名枚举,然后将 NSCalendarUnit 的类型定义为 NSUInteger。它们如何在 NSCalendarUnit 和匿名枚举之间链接。
在客户端代码中,我可以使用 NSUInteger 进行“或”操作,然后它们(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它们是使用
&
运算符取出的。这称为位字段,维基百科有一篇关于它们如何工作的不错的文章: http://en.wikipedia .org/wiki/Bit_field我最近还回答了一个关于按位运算符如何工作的问题:https://stackoverflow.com/问题/3427585#3427633
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_fieldI also answered a question recently on how bitwise operators work: https://stackoverflow.com/questions/3427585#3427633