1

I maybe naming it wrong, so please correct me.

I just want to know if this

if(!obj)
{
    //do something
}

is exactly the same as this

if(obj == nil)
{

}

I mean are they both checking whether the object points to nil?

JLT
  • 3,052
  • 9
  • 39
  • 86
  • @Larme thanks for the link. – JLT Nov 09 '16 at 12:14
  • I'll just add this link http://stackoverflow.com/questions/11821282/objectivec-if-obj-and-if-obj-nil-which-is-better where the top answerer seems to have done some research on the compilation code – Larme Nov 09 '16 at 12:16

2 Answers2

2

Yes, this is exactly the same. ! operator turns anything other than nil into zero, while nil becomes 1. Therefore, you get exactly the same results as the comparison with nil.

Similarly, using if (obj) is logically identical to if (obj != nil). This convention is inherited from C, where pointers are commonly used in conditions, and NULL-checked with ! operator.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Yes, it's the same. That's right. Yep.

joerick
  • 16,078
  • 4
  • 53
  • 57