Difference between ! and nil check on Objective-C

2019-08-29 08:47发布

问题:

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)

回答1:

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!