Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why nilObject isEqual nilObject return no?

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 ?

like image 732
Anthony Avatar asked Mar 20 '26 20:03

Anthony


2 Answers

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)

  • If the method returns any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.
  • If the method returns a 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.
  • If the method returns anything other than the aforementioned value types, the return value of a message sent to 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.

like image 162
Jacob Relkin Avatar answered Mar 24 '26 08:03

Jacob Relkin


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.

like image 21
Jim Avatar answered Mar 24 '26 07:03

Jim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!