When I use this code:
NSString *a = nil;
NSString *b = nil;
if([a isEqual:b]){
NSLog(@"YES");
}
else{
NSLog(@"NO");
}
The console print "NO" I don't understand this behavior. Could you explain me ?
The rules for sending messages to nilare as follows:
(Source: https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html#//apple_ref/doc/uid/TP30001163-CH11-SW7)
sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the struct. Other struct data types will not be filled with zeros.nil is undefined.(Thanks @Jim)
So for example, if you do this:
if(![nil someMessageThatAlwaysReturnsTrue]) {
NSLog(@"Watch this.");
}
It will print out "Watch this" every time.
See Sending Messages to nil
in The Objective-C Programming Language. When you send a message to an object that is nil and the method returns an object, the expression evaluates to nil itself, which is equivalent to 0, which is equivalent to NO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With