Brian Tracy
Brian Tracy

Reputation: 6831

Comparing Objects Directly to nil

I have seen many posts here on Stack Overflow warning Objective-C users not to compare objects with the == operator. For example, the following is always recommended against.

if (string1 == string2) {} // string1 and string2 are both of type NSString *

I understand this warning as the == operator in this case checks for pointer equality, not the actual values of string1 and string2. If this is the case, why do I so often see people comparing their objects to nil with the == operator. For example, I have seen the following several times.

if (obj == nil) {} // obj is of type id, or any other object

If comparing pointers with the == operator is bad practice on things like NSStrings (or NSNumbers or NSArrays etc), then why is it so commonplace with nil.

Is this the standard because there is only one type of nil i.e.: nil always equals nil?
Why are direct comaprisons using the == operator frowned upon between objects, but let slip when comparing to nil?

Thank your for your time.

Upvotes: 2

Views: 394

Answers (2)

CrimsonChris
CrimsonChris

Reputation: 4641

Using == tests for pointer equality, which seems to be what you want to test for in this particular case. You are checking whether some pointer is a nil pointer. Specifically, a pointer that equals zero. Comparing objects is more complicated as you've pointed out. Equality between objects often relies on some internal part of the two objects being "the same".

In the case of strings, "equality" can mean "has the same characters" but it could also mean "has the same characters (ignoring capitalization)". There are also cases where you might want a nil string to equal an empty string or even a string with just whitespace. The point is that you must understand the different methods of determining equality in order to implement your own definition of equality for your objects.

Note that checking for pointer equality is almost never what you want to use when comparing things like strings or arrays. There are some interesting optimizations that can throw you off. For example, all empty NSArray's point to the same singleton object.

Upvotes: 3

Shane Hsu
Shane Hsu

Reputation: 8357

nil is like NULL from C or std::nullptr in C++. Basically points to nothing.

When a object in Objective-C is unallocated (haven't been alloc), the pointer will be nil.

So if (obj == nil) will check if obj is allocated (or initialized as they often happen together)

This technique is often used when writing a custom initializer or checking if some object exists or not.

Upvotes: 1

Related Questions