使用NSDictionary到数组

时间:2015-07-03 16:26:19

标签: objective-c nsdictionary

我有2个NSArray内容ID,其他内容是网址

但是当我创建NSDictionary时,它看起来像这样(来自NSLog):

2015-07-03 17:10:51.072 hibridTesting[4950:166675] {
    (
) =     (
);
    (
    30,
    31
) =     (
    "https://www.google.com",
    "https://www.yahoo.com"
);
    (
    10,
    11,
    12,
    13
) =     (
    "https://www.facebook.com/",
    "https://www.sapo.pt",
    "https://www.sapo.pt",
    "https://www.sapo.pt"
);
    (
    20,
    21,
    22,
    23,
    24,
    25
) =     (
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com"
);
}

如果我这样做

arrayDeSitesSubmenus = [mydictionary objectForKey:@"21"];

如果我打印arrayDeSitesSubmenus,则会显示nil

我想要的是url的每个id,我理解的是一组url的键组

编辑:

来自数组的日志是:

2015-07-03 17:33:55.771 hibridTesting[5122:174427] (
    (
    "https://www.facebook.com/",
    "https://www.sapo.pt",
    "https://www.sapo.pt",
    "https://www.sapo.pt"
),
    (
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com",
    "https://www.google.com"
),
    (
    "https://www.google.com",
    "https://www.yahoo.com"
),
    (
),
    (
),
    (
),
    (
)
)
2015-07-03 17:33:55.771 hibridTesting[5122:174427] (
     (
    10,
    11,
    12,
    13
),
    (
    20,
    21,
    22,
    23,
    24,
    25
),
    (
    30,
    31
),
    (
),
    (
),
    (
),
    (
)
)

我从xmlparse获取数组,这就是为什么我的日志看起来像那样 感谢。

1 个答案:

答案 0 :(得分:0)

您是如何创建NSDictionary的?

创建NSDictionary时,您有两个选择:

第一

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", nil];

另一个是

NSDictionary *mdictionary = @{ @"key1" : @"value1" };

由于您已经拥有了键和值的数组,因此最适合您的是initWithObjects:forKeys,它接受​​值和键的数组并相应地进行排列。

NSArray *keys = @[@"1", @"2", @"3", @"4", @"5"];

NSArray *values = @[@"value1", @"value2", @"value3", @"value4", @"value5"];

NSDictionary *dictionary   = [[NSDictionary alloc] initWithObjects:values forKeys:keys];

,输出结果为:

{
    1 = value1;
    2 = value2;
    3 = value3;
    4 = value4;
    5 = value5;
}

但如果您的密钥是

之类的数字
NSArray *keys = @[@1, @2, @3, @4, @5];

NSArray *values = @[@"value1", @"value2", @"value3", @"value4", @"value5"];

NSDictionary *dictionary   = [[NSDictionary alloc] initWithObjects:values forKeys:keys];

//This is wrong and will return (null)
//
//NSLog(@"%@", [dictionary objectForKey:@"1"]); 

The correct one is:
NSLog(@"%@", [dictionary objectForKey:@1]);
or
NSLog(@"%@", [dictionary objectForKey:[NSNumber numberWithInt:1]]);

希望这对你有所帮助。干杯!