zakdances
zakdances

Reputation: 23685

How to tell the difference between BOOL values in a dict: NO, nil, or doesn't exist

I'm using a conditional statement such as

// isComplete is a BOOL value
if (![videoDictionary valueForKey:@"isComplete"]) {

    // do important things here

}

The problem is that this statement doesn't seem to be able to differentiate between NO, nil, and key doesn't exist. How can I make sure that this condition is met ONLY when isComplete is NO, and not when isComplete is nil or isComplete doesn't exist (no key)? How do I stop the false positives?

Upvotes: 0

Views: 139

Answers (2)

jscs
jscs

Reputation: 64002

This is not actually an issue. The dictionary cannot contain BOOLs directly, nor can it have nil as the value for a key. The value of the key @"isComplete" must be a valid object if it exists at all. If it's representing a boolean value, it's likely to be an NSNumber, and you should check the object's boolValue.

If the expression [someDictionary objectForKey:@"aKey"] evaluates as false, then it is only because there is no value for that key.

Upvotes: 1

Christian Stieber
Christian Stieber

Reputation: 12496

Do something similar to this:

NSNumber* IsComplete;
IsComplete=[videoDictionary objectForKey:@"isComplete"];
if (IsComplete!=nil && ![IsComplete boolValue])
{
   ...
}

Upvotes: 1

Related Questions