我想以字符串作为键以下列方式存储数据,我想将一个数组作为值。NSDictionary Objective-C
关键对象
“字母”{ 'A', 'B', 'C', 'd'}
“数字”{1,2,3,4,5,6,7}
这可能与代码NSDictionary
?如果是这样会怎样?我对此很困惑。
我想以字符串作为键以下列方式存储数据,我想将一个数组作为值。NSDictionary Objective-C
关键对象
“字母”{ '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"];
这将创建一个字符串数组和NSNumber
对象的数组的NSDictionary
,还有其他的方法来创建数组,但演示做一个基本途径。
每下面的评论:
如果你想项添加到阵列一次一个......
// 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
您可以将它们表示为属性列表。 Property-List Documentation。
<dict>
<key>letters</key>
<array>
<string>a</string>
<string>b</string>
<string>c</string>
<string>d</string>
</array>
<key>letters</key>
<array>
<integer>1</integer>
<integer>2</integer>
<integer>3</integer>
<integer>4</integer>
<integer>5</integer>
<integer>6</integer>
<integer>7</integer>
</array>
</dict>
有关如何序列化和可可去序列化数据的概述,请参阅Archives and Serialization Guide for Cocoa
假设你有一个名为NSArray
和letters
一个叫numbers
包含正确值:
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
letters, @"letters",
numbers, @"numbers",
nil
];
如果你想保持确保retain
10左右,或者使用alloc
和initWithObjectsAndKeys
。
有关更多详细信息,请参阅NSDictionary API参考。
有什么办法可以动态地做到这一点,以便我一次在代码中添加一个键/值对? – TheGambler 2009-05-26 03:05:23
做的事: [dict setObject:anObject forKey:@“key”]; 正在向字典添加键/值对。 – paulthenerd 2009-05-26 03:07:31