Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an NSDictionary in Objective-C?

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.

like image 201
vky Avatar asked Jan 26 '17 05:01

vky


People also ask

How do I create an NSDictionary in Objective-C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

How do I create an NSArray in Objective-C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is NSDictionary?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.


2 Answers

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] 
like image 173
Marco Avatar answered Oct 05 '22 21:10

Marco


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.

like image 35
Sverrisson Avatar answered Oct 05 '22 23:10

Sverrisson