How to create an NSDictionary in Objective-C? How to create an NSDictionary in Objective-C? ios ios

How to create an NSDictionary in Objective-C?


You should use a combination of arrays and dictionaries.

Dictionaries are initialized like this:

NSDictionary *dict = @{ key : value, key2 : value2};

Arrays are initialized like this:

NSArray *array = @[Object1, Object2]


Objective-C the correct, typed way of creating a dictionary.

The following has a strongly typed key as NSString and the value as NSNumber.

You should always set the types where you can, because by making it strongly typed the compiler will stop you from making common errors and it works better with Swift:

NSDictionary<NSString *, NSNumber *> *numberDictionary;

but in the case above, we need to store an array in the dictionary, so it will be:

NSDictionary<NSString *, id> *dataDictionary;

which allows the value to be of any type.