How to create an NSDictionary in Objective-C?
52,964
Solution 1
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]
Solution 2
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.
Author by
vky
Updated on July 14, 2022Comments
-
vky almost 2 years
I want to create an NSDictionary like this type:
"zones": { { "zoneId": "1", "locations": { { "locId": "1", "locZoneId": "1", "locLatitude": "33.68506785633641", "locLongitude": "72.97488212585449" }, { "locId": “2”, "locZoneId": "1", "locLatitude": "33.68506785633641", "locLongitude": "72.97488212585449" }, { "locId": “3”, "locZoneId": "1", "locLatitude": "33.68506785633641", "locLongitude": "72.97488212585449" }, } } }
But I don't know how to create.