retrodev
retrodev

Reputation: 2393

Difference between ! and nil check on Objective-C object

I'm teaching myself Objective-C 2.0.

I see from various code samples, the following two approaches to test if an object has been initialised. If that's not exactly what these tests do, please correct me.

Can you please explain the difference between the following:

if (!myObject)

and

if (myObject == nil)

Upvotes: 0

Views: 629

Answers (1)

Groot
Groot

Reputation: 14251

All objects are set to nil in the alloc method (or to zero for instance variables). Both of your cases checks if the object is equal to nil (is not initialized) and both will work. They are equivalent to each other. It is a matter of taste which one you prefer. Personally I tend to use

if (!myObject)

because it is my personal preference. Hope it helps!

Upvotes: 4

Related Questions