如何创建一个包含每个键的数组的NSDictionary?
我想知道如何(如果有可能)创建一个NSDictionary为每个键保存一个NSArray。如何创建一个包含每个键的数组的NSDictionary?
类似的东西:
@ “FirstKey” - [0],[1],[2],[3]
@ “SecondKey” - [0],[1],[2] ,[3]
@“ThirdKey” - [0],[1],[2],[3]
@“FourthKey” - [0],[1],[2],[3]
希望你有想法,谢谢!
您可以添加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.
另外,如果你没有太多的键/值:
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];
是的,你可以在字典中存储任何对象。对于数字值,您需要将它们存储为NSValue或NSNumber对象。
这完全有可能。最简单的方法是创建您的NSArray,然后再加上一点为对象,关键看你的NSDictionary
NSArray *myArray = [NSArray arrayWithObjects:@"One",@"Two", nil];
[myDictionary setObject:myArray forKey:@"FirstKey"];
有什么方法可以在实例方法中创建该方法吗? – Itamar
是的,只需使用'[NSDictionary initWithObjectsAndKeys:[NSArray arrayWithObjects:@“One”,@“Two”,nil],@“FirstKey”,nil];' –
我想创建一个NSDictionary,每一个键是一个字符串,并拥有一个NSArray – Itamar
是的,NSArray只是另一种对象。 – Dancreek