NSDictionary Objective-C

后端 未结 3 494
死守一世寂寞
死守一世寂寞 2021-01-14 13:17

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\"

相关标签:
3条回答
  • 2021-01-14 13:59

    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

    0 讨论(0)
  • 2021-01-14 14:03

    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.

    0 讨论(0)
  • 2021-01-14 14:16

    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
    
    0 讨论(0)
提交回复
热议问题