我正在尝试以字符串作为键以以下方式存储数据,我想要一个数组作为值。
关键对象
“字母”{'a','b','c','d'}
“数字”{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
对象数组,还有其他创建数组的方法,但它演示了一种基本方法.
根据以下评论:
如果您想一次向数组添加项目...
// 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
关于objective-c - NSDictionary Objective-C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/908742/