0

我正在传递一本字典:

aDictionary

当我将其注销时,字典具有以下格式:

{
 value1 = "subValue1 {label=value1, info1=, info2=}";
 value2 = "subValue2 {label=value2, info1=, info2=}";
 value3 = "subValue3 {label=value2, info1=, info2=}";
 }

我需要遍历字典,然后确定 value3 -> subValue3 -> info2 是否有值。

我可以进行初始迭代,并且可以制作该行的子字典:

"subValue3 {label=value2, info1=, info2=}"

但是当我尝试使用它时,比如获取键的计数,我得到 -[subValue3 allKeys]: unrecognized selector sent to instance。

NSArray *keys;
int i, count;
id key, value;

keys = [aDictionary allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
    key = [keys objectAtIndex:i];
    value = [aDictionary objectForKey:key];
    NSLog (@"Key: %@ for value: %@", key, value);

    NSDictionary *subDictionary = [aDictionary objectForKey:key];
    if ([key isEqualToString:@"info2"]) {
        DLog(@"subDictioanry = %@", subDictionary);
        // Everything is fine up to here
        NSArray *keys2;
        int i2, count2;
        id key2, value2;

        keys2 = [subDictionary allKeys];
        count = [keys2 count];
        //
        // Right here I get "-[subValue3 allKeys]: unrecognized selector sent to instance"
        //
        for (i2 = 0; i2 < count2; i2++) {
            key2 = [keys2 objectAtIndex:i2];
            value = [subDictionary objectForKey:key];
            DLog (@"Key: %@ for value: %@", key2, value2);

            NSDictionary *subDictionary2 = [subDictionary objectForKey:key2];
            DLog(@"subDictionary2 = %@", subDictionary2);
        }
    }

问题:我不确定第二组值的格式是什么(“subValue3 {label=value2, info1=, info2=}”)。它是集合、数组还是字典?如何将该组放入字典中(不会在键(?)“subValue3”上失败),以便我可以检查键 info2 是否有任何值?

免责声明:我知道有更有效的方法来遍历字典,我只是想尽可能清楚。我确定我缺少一些基本的东西,但我没有在 Apple 文档中看到关于迭代或 NSDictionary 的答案,也没有找到关于第二组格式的任何信息。谢谢!

4

1 回答 1

0

现在"subValue1 {label=value1, info1=, info2=}";是一个NSString。所以allKeysNSString崩溃。

事实上,这"subValue1 {label=value1, info1=, info2=}";看起来像一个有效的 json。我不认为这是一个有效的 JSON。甚至jsonlint.com也这么认为。

这是一个有效的 json

{
    "subValue1": {
        "label": "value1",
        "info1": "",
        "info2": ""
    }
}

像这样构造json之后,然后使用NSJSONSerialization转换-

NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];

if (!jsonDict) 
{
  NSLog(@"Error parsing JSON: %@", e);
} else 
{
   for(NSDictionary *item in jsonDict) 
      NSLog(@"Item: %@", item);
}
于 2012-12-07T04:07:40.777 回答