我正在尝试以字符串作为键以下列方式存储数据,我希望将数组作为值.
关键对象
"letters"{'a','b','c','d'}
"数字"{1,2,3,4,5,6,7}
NSDictionary在代码中这可能吗?如果是这样,那会是什么样子?我真的很困惑.
pau*_*erd 16
在代码中执行此操作的简单方法(并且只是您可以执行此操作的多种方法之一):
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"];
Run Code Online (Sandbox Code Playgroud)
这创建了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
Run Code Online (Sandbox Code Playgroud)
假设你有一个NSArray被叫letters和一个numbers包含正确值的被叫:
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
letters, @"letters",
numbers, @"numbers",
nil
];
Run Code Online (Sandbox Code Playgroud)
确保retain如果你想留下dict来,或者使用alloc和initWithObjectsAndKeys.
有关更多详细信息,请参阅NSDictionary API参考.
| 归档时间: |
|
| 查看次数: |
18830 次 |
| 最近记录: |