ios 如何在 Objective-C 中创建 NSDictionary?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41867536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 11:05:52  来源:igfitidea点击:

How to create an NSDictionary in Objective-C?

iosobjective-cnsdictionarynsmutabledictionary

提问by vky

I want to create an NSDictionary like this type:

我想创建一个像这种类型的 NSDictionary:

"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.

但我不知道如何创建。

回答by Marco

You should use a combination of arrays and dictionaries.

您应该使用数组和字典的组合。

Dictionariesare initialized like this:

字典初始化如下:

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

Arraysare initialized like this:

数组初始化如下:

NSArray *array = @[Object1, Object2]

回答by Sverrisson

New Objective-C correct, typed way of creating dictionary.

新的 Objective-C 正确的键入方式创建字典。

The following has a strongly typed keyas NSStringand the valueas NSNumber.

下面有一个强类型的keyasNSStringvalueas NSNumber

You should get in the habit of always setting 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:

您应该养成始终在可能的地方设置类型的习惯,因为通过将其设置为强类型,编译器将阻止您犯常见错误,并且它与 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.

这允许值是任何类型。