John
John

Reputation: 21

Objective-C: testing for an unassigned (undefined) variable?

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

Upvotes: 2

Views: 4045

Answers (2)

paxdiablo
paxdiablo

Reputation: 881223

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

Upvotes: 1

Grant Paul
Grant Paul

Reputation: 5902

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;

Upvotes: 4

Related Questions