NSDictionary Objective-C [英] NSDictionary Objective-C
问题描述
键对象
我尝试以下列方式存储数据,以字符串为键,我想要一个数组作为值。 >字母{'a','b','c','d'}
numbers{1,2,3,4 ,5,6,7}
在代码中 NSDictionary
如果是这样,怎么样?我真的很困惑这个。
在代码中做一个简单的方法可以这样做):
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
[dict setObject:[NSArray arrayWithObjects:@a,@b,@c,@d,nil] forKey:@letters
[dict setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],[NSNumber numberWithInt:3],[NSNumber numberWithInt:4],nil] forKey:@numbers];
这会创建一个 NSDictionary
字符串和 NSNumber
对象的数组,还有其他方法来创建数组,但它演示了一个基本的方法。
根据以下注释:
如果您想一次添加一个项目到数组...
//创建字典并添加字母和数字mutable arrays
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
NSMutableArray * letters = [NSMutableArray array];
NSMutableArray * numbers = [NSMutableArray array];
[dict setObject:letters forKey:@letters];
[dict setObject:numbers forKey:@numbers];
//添加一个字母并添加一个数字
[[dict objectForKey:@letters] addObject:@a];
[[dict objectForKey:@numbers] addObject:[NSNumber numberWithInt:1]];
//现在有一个NSDictionary(hash),有两个数组,一个字母和一个数字
//,字母数组中的字母'a'和
中的数字1 //数字数组
I'm trying to store data in the following fashion with a string as the key and I would like an array as the value.
key objects
"letters" {'a','b','c','d'}
"numbers" {1,2,3,4,5,6,7}
Is this possible with NSDictionary
in code? If so how would that look like? I'm really confused on this.
A simple way to do this in code (and just one of many several ways you could do it):
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSArray arrayWithObjects:@"a", @"b", @"c", @"d", nil] forKey:@"letters"];
[dict setObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil] forKey:@"numbers"];
That creates an NSDictionary
with an array of strings and an array of NSNumber
objects, there are other ways to create arrays, but that demonstrates a basic way to do it.
Per the comments below:
If you wanted to add items to the arrays one at a time...
// create the dictionary and add the letters and numbers mutable arrays
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSMutableArray *letters = [NSMutableArray array];
NSMutableArray *numbers = [NSMutableArray array];
[dict setObject:letters forKey:@"letters"];
[dict setObject:numbers forKey:@"numbers"];
// add a letter and add a number
[[dict objectForKey:@"letters"] addObject:@"a"];
[[dict objectForKey:@"numbers"] addObject:[NSNumber numberWithInt:1]];
// This now has an NSDictionary (hash) with two arrays, one of letters and one
// of numbers with the letter 'a' in the letters array and the number 1 in
// the numbers array
这篇关于NSDictionary Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!