2

If I've created these two variables:

NSDecimalNumber *myNum;
NSString *myString;

how do I later test whether an object has been assigned to them yet or not?

Thanks

2 Answers 2

4

If they aren't in a class, you must assign nil as a default value if you want to use this. In a class, that will be automatic.

To test if they have an object associated with them, compare them against nil: if (myNum != nil) // myNum is an object.

Also note that when an object is deallocated, references to it still exist, so when you release ownership of these objects it is good to set them back to nil: myNum = nil;

Sign up to request clarification or add additional context in comments.

2 Comments

To clarify, instance variables and static variables get initialized to nil for free. Local variables and non-static global variables don't.
Note that with ARC, local object pointers are also initialized to nil.
1

Set it to nil to start with:

NSDecimalNumber *myNum = nil;

Then use:

if (myNum == nil) { ... you haven't set it yet ... }

nil is the ObjC way of doing null objects (those that do not refer to an actual object).

2 Comments

nil and NULL are the same value, they just may be slightly different types (nil an id, NULL a void *). You can send a message to NULL; you may get a warning (or not), but it won't crash.
Thanks, @Peter, I actually meant the equivalent operation in C or C++ which would result in dereferencing a null pointer, but I've taken that bit out entirely since it didn't really add to the answer that much.

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.