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\"
You can represent them as property-lists. 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>
For an overview of how to serialize and de-serialize your data in Cocoa, see Archives and Serialization Guide for Cocoa
Assuming you have an NSArray
called letters
and one called numbers
containing the correct values:
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
letters, @"letters",
numbers, @"numbers",
nil
];
Make sure to retain
if you want to keep dict
around, or alternatively use alloc
and initWithObjectsAndKeys
.
See NSDictionary API reference for more details.
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