Reputation: 700
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 ? What the difference between the definition of isEqual: and == operator ?
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. I need to conversion vice versa also.
Upvotes: 1
Views: 416
Reputation: 11004
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
). 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
.
The isEqual:
method
The isEqual:
method simply compares the two NSObjects
to see if they are the same value, but not necessarily the exact same object. [x isEqual:y]
asks, "is x
the same as y
?", whereas x==y
asks, "does x
point to the same object as 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:
. The isEqual:
method compares the value of two objects rather than the objects themselves.
Also, [NSNumber numberWithBool:NO]
and [NSNumber numberWithUnsignedInt:0]
do actually yield the same value, which is why isEqual:
returns true.
Upvotes: 5