xcode 如何创建一个包含每个键的数组的 NSDictionary?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6512198/
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-09-14 21:22:19  来源:igfitidea点击:

How to create an NSDictionary that contains an array for every key?

iphoneobjective-cxcodensarraynsdictionary

提问by Itamar


I wanted to know how (if it is possible) to create an NSDictionary that holds an NSArray for every key.


我想知道如何(如果可能的话)创建一个 NSDictionary 来为每个键保存一个 NSArray。

Something like that:

类似的东西:

@"FirstKey" - [0], [1], [2], [3]
@"SecondKey" - [0], [1], [2], [3]
@"ThirdKey" - [0], [1], [2], [3]
@"FourthKey" - [0], [1], [2], [3]

@"FirstKey" - [0], [1], [2], [3]
@"SecondKey" - [0], [1], [2], [3]
@"ThirdKey" - [0], [ 1], [2], [3]
@"FourthKey" - [0], [1], [2], [3]

Hope you got the idea, thanks ahead!

希望你有这个想法,提前谢谢!

回答by Barry Wark

You can add NSArrayinstances (or any other collection) as values of an NSDictionary:

您可以添加NSArray实例(或任何其他集合)作为 的值NSDictionary

NSDictionary *d = [[NSMutableDictionary alloc] init];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0], 
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"FirstKey"];
[d setValue:[NSArray arrayWithObjects:
               [NSNumber numberWithInteger:0], 
               [NSNumber numberWithInteger:1],
               ...,
               nil]
     forKey:@"SecondKey"];
//etc.

Alternatively, if you don't have too many keys/values:

或者,如果您没有太多键/值:

NSArray *values1 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0], 
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSArray *values2 = [NSArray arrayWithObjects:
                    [NSNumber numberWithInteger:0], 
                    [NSNumber numberWithInteger:1],
                    ...,
                    nil];
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                     values1, @"FirstKey",
                     values2, @"SecondKey",
                     ...,
                     nil];

回答by Nick Bull

That's totally possibly. Simplest way is to create your NSArray and then just add that as the object for the key to your NSDictionary

这完全有可能。最简单的方法是创建您的 NSArray,然后将其添加为 NSDictionary 键的对象

NSArray *myArray = [NSArray arrayWithObjects:@"One",@"Two", nil];
[myDictionary setObject:myArray forKey:@"FirstKey"];

回答by Dancreek

Yes, you can store any object in a dictionary. For numeric values you will need to store them as NSValue or NSNumber objects.

是的,您可以将任何对象存储在字典中。对于数值,您需要将它们存储为 NSValue 或 NSNumber 对象。