Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an NSDictionary or NSMutableDictionary contains a key?

I need to check if an dict has a key or not. How?

like image 731
dontWatchMyProfile Avatar asked May 06 '10 21:05

dontWatchMyProfile


People also ask

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

How do I check if a dictionary is null in Objective C?

Sending a message to nil / NULL is always valid in Objective-C. So it depends if you want to check if a dictionary is nil , or if it doesn't have values (as a valid dictionary instance may be empty). In the first case, compare with nil . Otherwise, checks if count is 0, and ensure you're instance is still valid.

What is the difference between NSMapTable vs NSDictionary?

NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


2 Answers

objectForKey will return nil if a key doesn't exist.

like image 93
Adirael Avatar answered Oct 06 '22 00:10

Adirael


if ([[dictionary allKeys] containsObject:key]) {     // contains key } 

or

if ([dictionary objectForKey:key]) {     // contains object } 
like image 31
Aleksejs Mjaliks Avatar answered Oct 06 '22 01:10

Aleksejs Mjaliks