Difference between ! and nil check on Objective-C

2019-08-29 07:53发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-08-29 08:57

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!

查看更多
登录 后发表回答