简体   繁体   English

NSNumber:NO == 0?

[英]NSNumber: NO == 0?

NSNumber *x = [NSNumber numberWithBool:NO];
NSNumber *y = [NSNumber numberWithUnsignedInt:0];
assert([x isEqual:y]);
assert(x==y);

The first assertion passes and the second one fails, why ? 第一个断言通过了,而第二个断言失败了,为什么? Because their 'objCType' are different ? 因为他们的'objCType'是不同的? What the difference between the definition of isEqual: and == operator ? isEqual:和==运算符的定义之间有什么区别?

Why I am doing this: I have to store a boolean value in some backend whose API requires an NSNumber instead of BOOL so I have to convert all BOOL to NSNumber before storing them. 为什么这样做:我必须在其API需要NSNumber而不是BOOL的某些后端中存储布尔值,因此在存储它们之前必须将所有BOOL转换为NSNumber。 I need to conversion vice versa also. 反之亦然,我也需要转换。

The == operator ==运算符

The == operator compares natively typed values, as well as object pointers to see if they are exactly the same. ==运算符比较本机类型的值以及对象指针以查看它们是否完全相同。 This would be useful is you want to see if two natively typed values are equal ( 1 == 1 , where 1 is an int ). 如果您想查看两个本机类型的值是否相等( 1 == 1 ,其中1是int ),这将很有用。 It also lets you see if two pointers point to the same object. 它还可以让您查看两个指针是否指向同一对象。 For example, if you had this: 例如,如果您有:

NSNumber *x = [NSNumber numberWithBool:NO];
NSNumber *y = x;

then x==y is true, since x is pointing to the same object as y . 那么x==y为真,因为x指向与y相同的对象。

The isEqual: method isEqual:方法

The isEqual: method simply compares the two NSObjects to see if they are the same value , but not necessarily the exact same object . isEqual:方法只是比较两个NSObjects以查看它们是否具有相同的 ,但不一定是相同的对象 [x isEqual:y] asks, "is x the same as y ?", whereas x==y asks, "does x point to the same object as y ?" [x isEqual:y]询问“ xy是否相同?”,而x==y询问“ x指向与y相同的对象吗?”

(Remember, when you use an * , you are declaring a pointer.) (请记住,当您使用* ,您是在声明一个指针。)

Conclusion 结论

Since you are not using natively typed values or pointers, you should use isEqual: . 由于未使用本机类型的值或指针,因此应使用isEqual: The isEqual: method compares the value of two objects rather than the objects themselves. isEqual:方法比较两个对象的值,而不是对象本身。

Also, [NSNumber numberWithBool:NO] and [NSNumber numberWithUnsignedInt:0] do actually yield the same value, which is why isEqual: returns true. 另外, [NSNumber numberWithBool:NO][NSNumber numberWithUnsignedInt:0]实际上会产生相同的值,这就是为什么isEqual:返回true的原因。

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

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