简体   繁体   English

修饰符标志:NSInteger是否足够?

[英]Modifier Flags: NSInteger enough?

Is an NSInteger enough to keep track of a modifier flags? NSInteger是否足以跟踪修饰符标志? (cmd / alt / ctrl etc). (cmd / alt / ctrl等)。

I notice that on an event it returns an NSUinteger (unsigned) ([theEvent modifierFlags]) instead of an NSInteger, but from my testing it appears to be working just fine when I save the modifier mask in an NSInteger. 我注意到,在事件上它返回NSUinteger(无符号)([theEvent修饰符标记]),而不是NSInteger,但是从我的测试来看,当我将修饰符掩码保存在NSInteger中时,它似乎工作得很好。

I need an NSInteger because I'm saving the modifier mask as the tag of certain controls. 我需要一个NSInteger,因为我将修饰符掩码保存为某些控件的标签。

NSInteger and NSUInteger are the same size (ie. same number of bits). NSInteger和NSUInteger的大小相同(即,位数相同)。 The difference is whether the bits are considered to represent a signed or unsigned number when performing arithmetic, etc. If you're only ever manipulating the number with bitwise operations, it won't really matter. 区别在于,在执行算术等操作时,是将这些位视为代表带符号的数字还是无符号的数字。如果仅使用按位运算来操作数字,则实际上并不重要。 That said, you should use the same type that the method in question returns, in this case NSUInteger. 也就是说,您应该使用与所讨论方法返回的类型相同的类型,在这种情况下为NSUInteger。 The reason for using an unsigned here is that when the value in question is really a bunch of bits to be set/cleared independently, it doesn't make sense conceptually for that value to have a sign bit. 在此处使用无符号的原因是,当所讨论的值实际上是一堆要独立设置/清除的位时,从概念上讲,该值具有符号位是没有意义的。

As Andrew said, i just want to add something. 正如安德鲁所说,我只想添加一些内容。 If you are using bitflags as it seems from your question in iOS 6 they introduced a new macro, that seems the new "Apple way" 如果您使用的是位标记,那么从iOS 6中的问题可以看出,它们引入了一个新的宏,这似乎是新的“ Apple方式”

typedef NS_OPTIONS(NSInteger, CustomType) {
    kCmdKey = 1 << 0,
    kAltKey = 1 << 1,
    ctrlKey = 1 << 2,
};

there is also a macro NS_ENUM, for enums that are not used as bitmasks. 还有一个宏NS_ENUM,用于不用作位掩码的枚举。 in both NS_OPTIONS and NS_ENUM you can specify the type to use (NSInteger) and your typedef type name. 在NS_OPTIONS和NS_ENUM中,您都可以指定要使用的类型(NSInteger)和typedef类型名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM