While I compare two NSNumbers using isEqualToNumber, it is returning a false if both numbers are nil. Why a comparison of sort [nil isEqual:nil] always returns false while nil == nil returns true ?
Asked
Active
Viewed 1,091 times
2
krishnanunni
- 510
- 7
- 16
2 Answers
4
It is the standard behaviour. You will get the same result from isEqueslToString: etc. It is better this way, because you could have for example weak references to unequal objects, which would become equal uppon deallocation.
You can use a condition like number1.intValue == number2.intValue in which case it would return YES for 2 nil objects. However, you will also get YES for nil.intValue == @0.intValue
Levi
- 7,313
- 2
- 32
- 44
-
I guessed it will be the default behaviour. But can you tell me what is the concept behind returning false. Its just curiosity. – krishnanunni Feb 18 '15 at 08:59
-
1It would be the source of many errors in case it would work differently, just look at the example I gave with the `weak` reference. It is like you would compare the addresses of 2 houses. If they have the same address, then you can say that these are equal. But if you take 2 houses and neither has an address, you cannot say that you were talking about the same houses. A little far-fetched comparison, but I hope you'll get the point – Levi Feb 18 '15 at 09:10
-
Thanks. Nice example. That settles my curiosity. – krishnanunni Feb 18 '15 at 09:28
0
[nil isEqual:nil] compares objects while nil == nil compares pointers.
Pointer to nil is always equal to pointer to nil. On the other hand object that does not exist is not equal to anything.
Wojtek
- 1,006
- 11
- 30
-
`[nil isEqual:someObjectPointer]` sends a message to nil, which returns 0 by definition. See https://stackoverflow.com/q/156395/86436 – splicer Mar 18 '19 at 17:48