Methods for checking for a valid object in Objective C?
Fo开发者_StackOverflowr an instance of myObject, is there a difference between
if (myObject == nil)
and
if (myObject)
My assumption is that if myObject hasn't been allocated and initialized, it will be nil and the two are synonymous.
UPDATE: I'm sorry, I mis-worded my question but I think you answered what I was really asking. Let me clarify:
I have two tableViews, each with its own viewController, tblVC1
and tblVC2
. For a user tap on a table row, the viewController configures a popver contentViewController, contentVC
, which has tblVC1 and tblVC2 properties. So if the user tap is handled by tblVC1
, it sets contentVC.tblVC1 = self
, and the tblVC2
property is not initialized.
When I need to call back to the launching viewController I have been checking for which viewController to call like this:
if (tblVC1) {
[tlbVC1 callTheMethod];
} else {
[tlbVC2 callTheMethod];
}
So I should have asked: is if (tblVC1)
the same as if (tblVC1 != nil)
?if(myObject)
checks if myObject points to an memory area != 0x0 and if(myObject == nil)
checks if myObject points to 0x0.
Oh, and myObject won't be NULL by default, but only if it is an ivar of an ObjC class, otherwise it will point to a random memory chunk.
(Disclaimer: Requesting a new memory page on iOS and Mac OS X will result in a clean memory page which means that myObject would be NULL in this case. But I wouldn't rely on this)
Correct. A detailed discussion of nil
and default values is available on Cocoa with Love.
Edit: JustSid is right to point out that this is only guaranteed of instance variables.
精彩评论