NSDictionary Objective-C

后端 未结 3 497
死守一世寂寞
死守一世寂寞 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 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
    

提交回复
热议问题