获取多维字典的所有键

时间:2016-01-22 05:13:47

标签: objective-c dictionary

我有一本字典:

{
dataTypes =     (
            {
        dataType = "datatype1";
        editable = 1;
        maxValue = 300;
        minValue = 0;
        order = 1;
        title = "Title 1";
        type = numeric;
        units = kg;
    },
            {
        dataType = "datatype 2";
        editable = 1;
        maxValue = 300;
        minValue = 0;
        order = 2;
        title = "title2";
        type = numeric;
        units = gm;
    },
            {
        dataType = "datatype3";
        editable = 1;
        maxValue = 300;
        minValue = 20;
        order = 3;
        title = "title3";
        type = numeric;
        units = kg;
    }
);
name = "Name";
order = 1
title = "Title";
}

我想要获取此词典中的所有键。

我尝试了[myDict allKeys],但这只返回了四个键:DataTypesnameordertitle

我想检索所有密钥:dataTypeeditablemaxvalue等。

2 个答案:

答案 0 :(得分:0)

试试这个。

NSArray *tempArray = [myDict objectForKey:@"dataTypes"];

NSDictionary *tempDictionary = (NSDictionary *)tempArray[0];

[tempDictionary allKeys]将拥有你想要的东西。

写下这个方法。

- (NSDictionary *)dictionaryFromArrayWithinDictionary:(NSDictionary *)dictionary withKey:(NSString *)key{
    NSArray *tempArray = [dictionary objectForKey:key];
    return (NSDictionary *)tempArray[0]; 
}

这将返回内部字典并简单地在此字典上调用“allKeys”,您将获得所需的所有键。

答案 1 :(得分:0)

您需要递归遍历字典,并通过字典可能包含的任何数组,依此类推。这可以通过添加到所有对象的recursiveKeys方法很好地完成,该方法为非容器的对象返回一个空数组,并遍历容器对象的容器:

@interface NSObject(MyCategory)
- (NSArray)recursiveKeys;
@end

@implementation NSObject(MyCategory)
- (NSArray)recursiveKeys {
    return @[];
}
@end

@implementation NSArrray(MyCategory)
- (NSArray)recursiveKeys {
    NSMutableArray *result = [NSMutableArray array];
    for (id item in self) {
        [result addObjectsFromArray:[item recursiveKeys]];
    }
    return [result copy]; //return an immutable array
}
@end

@implementation NSSet(MyCategory)
- (NSArray)recursiveKeys {
    NSMutableArray *result = [NSMutableArray array];
    for (id item in self) {
        [result addObjectsFromArray:[item recursiveKeys]];
    }
    return [result copy]; //return an immutable array
}
@end

@implementation NSDictionary(MyCategory)
- (NSArray)recursiveKeys {
    NSMutableArray *result = [self.allKeys mutableCopy];
    for (id key in self) {
        [result addObjectsFromArray:[self[key] recursiveKeys];
    }
    return [result copy]; //return an immutable array
}
@end

你可以像这样使用它:

NSArray *keys = myDictionary.recursiveKeys;

请原谅任何语法错误,我目前没有Xcode在我面前,我只是在SO上输入代码。