简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM