Working with nil

Working with nil

  It’s always a good idea to initialize scalar variables at the time you declare them, otherwise their initial values will contain garbage from the previous stack contents:

  

  This isn’t necessary for object pointers, because the compiler will automatically set the variable to nil if you don’t specify any other initial value:

  

  A nil value is the safest way to initialize an object pointer if you don’t have another value to use, because it’s perfectly acceptable in Objective-C to send a message to nil. If you do send a message to nil, obviously nothing happens.

  Note: If you expect a return value from a message sent to nil, the return value will be nil for object return types, 0 for numeric types, and NO for BOOL types. Returned structures have all members initialized to zero.

  If you need to check to make sure an object is not nil (that a variable points to an object in memory), you can either use the standard C inequality operator:

  

  or simply supply the variable:

  

  If the somePerson variable is nil, its logical value is 0 (false). If it has an address, it’s not zero, so evaluates as true.

Similarly, if you need to check for a nil variable, you can either use the equality operator:

  

  or just use the C logical negation operator:

  

原文地址:https://www.cnblogs.com/tekkaman/p/3550942.html