【问题标题】:How to create an NSDictionary that contains an array for every key?如何创建一个包含每个键的数组的 NSDictionary?
【发布时间】:2011-06-28 19:41:34
【问题描述】:


我想知道如何(如果可能的话)创建一个为每个键保存一个 NSArray 的 NSDictionary。

类似的东西:

@"FirstKey" - [0]、[1]、[2]、[3]
@"SecondKey" - [0]、[1]、[2]、[3]
@"第三键" - [0]、[1]、[2]、[3]
@"FourthKey" - [0]、[1]、[2]、[3]

希望你明白了,谢谢!

【问题讨论】:

    标签: iphone objective-c xcode nsarray nsdictionary


    【解决方案1】:

    您可以添加NSArray 实例(或任何其他集合)作为NSDictionary 的值:

    NSDictionary *d = [[NSMutableDictionary alloc] init];
    [d setValue:[NSArray arrayWithObjects:
                   [NSNumber numberWithInteger:0], 
                   [NSNumber numberWithInteger:1],
                   ...,
                   nil]
         forKey:@"FirstKey"];
    [d setValue:[NSArray arrayWithObjects:
                   [NSNumber numberWithInteger:0], 
                   [NSNumber numberWithInteger:1],
                   ...,
                   nil]
         forKey:@"SecondKey"];
    //etc.
    

    或者,如果您没有太多键/值:

    NSArray *values1 = [NSArray arrayWithObjects:
                        [NSNumber numberWithInteger:0], 
                        [NSNumber numberWithInteger:1],
                        ...,
                        nil];
    NSArray *values2 = [NSArray arrayWithObjects:
                        [NSNumber numberWithInteger:0], 
                        [NSNumber numberWithInteger:1],
                        ...,
                        nil];
    NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
                         values1, @"FirstKey",
                         values2, @"SecondKey",
                         ...,
                         nil];
    

    【讨论】:

      【解决方案2】:

      这完全有可能。最简单的方法是创建你的 NSArray,然后将它作为对象添加到你的 NSDictionary

      NSArray *myArray = [NSArray arrayWithObjects:@"One",@"Two", nil];
      [myDictionary setObject:myArray forKey:@"FirstKey"];
      

      【讨论】:

      • 有没有办法在实例方法中创建?
      • 是的,只需使用[NSDictionary initWithObjectsAndKeys:[NSArray arrayWithObjects:@"One",@"Two",nil], @"FirstKey", nil];
      【解决方案3】:

      是的,您可以将任何对象存储在字典中。对于数值,您需要将它们存储为 NSValue 或 NSNumber 对象。

      【讨论】:

      • 我想创建一个 NSDictionary,其中每个键都是一个字符串并保存一个 NSArray
      • 是的,NSArray 只是另一种对象。
      猜你喜欢
      • 1970-01-01
      • 2019-10-05
      • 2019-09-03
      • 1970-01-01
      • 2023-04-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多