views:

168

answers:

3

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

+4  A: 

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;

chpwn
To clarify, instance variables and `static` variables get initialized to `nil` for free. Local variables and non-`static` global variables don't.
Peter Hosey
+1  A: 

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).

paxdiablo
`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.
Peter Hosey
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.
paxdiablo
A: 

I'm not able to make follow-up comments. Thank you chpwn and paxdiablo -- that answers it for me.

John
Then you should mark one of the responses as answering your question.
Rob Keniger