0

In AS3, I would often do something like this

if(myObject != null)
{
  //if we get here then myObject is ready to go

}
else
{
  //myObject = null so we need to set it up
}

In Obj-c I understand you initialise an object like this...

myObject = [[NSObject alloc] init];

But how would I do a similar check in obj-c, as I would do in AS3, and/or is that the best way to do that? should there be another way to know if an object has already been initialised and if it hasn't set up?

So when I'm done with the object in AS3, I just need to do

myObject = null;

And the code knows to set it up next time it comes to that conditional code.

1
  • 1
    test against nil or NULL - but wasn't this in the Objective-C tutorial that you do have read? Commented Oct 29, 2012 at 22:34

2 Answers 2

4

You do it the same way. The null pointer in Objective-C is nil.

if (myObject != nil) {
   // do something
} else {
   // do something else 
}

Objective-C can also treat any object as a boolean (if the object is nil (0), the boolean will be false), so you can leave out nil too:

if (myObject) {
    // do something
} else {
    // do something else 
}
Sign up to request clarification or add additional context in comments.

4 Comments

"casting to a boolean" is not entirely precise, no cast occurs in the 2nd case, it's only that nonzero numerical values will be treated as true.
Minor nitpick - In your 2nd bit of code, that isn't casting. In C, any value of 0 is treated as false, and non-zero value is treat as true. So a nil object reference is 0 so it's treated as false. No casting is done.
I'm using ARC, does that complicate matters any with setting an object to nil?
@DrummerB I guess `C treats all nonzero numerical values as a true condition' would suffice.
1

Use nil in Objective-C.

if (myObject != nil) {
}

or even easier:

if (myObject) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.