如何在NSDictionary iphone中获取未知密钥的值?

时间:2011-11-25 13:35:21

标签: iphone web-services nsdictionary

在解析Webservice响应中的值时,我还有一个大问题。我不知道webservice响应中值的关键。例如,

class =     (
                {
            "ObjectiveC" =   
         (
                                {
                    "brief_desc" = "ObjectiveC";
                    date = "2008-02-27";
                    "event_status" = Attended;
                },
                                {
                    "brief_desc" = "ObjectiveC";
                    date = "2008-03-05";
                    "event_status" = Attended;
                },
                                {
                    "brief_desc" = "ObjectiveC";
                    date = "2008-03-12";
                    "event_status" = Missed;
                },
            ); 
        },
                {
            "Java" =             (
 {
                    "brief_desc" = "Java";
                    date = "2008-02-27";
                    "event_status" = Attended;
                },
                                {
                    "brief_desc" = "Java";
                    date = "2008-03-05";
                    "event_status" = Attended;
                },
                                {
                    "brief_desc" = "Java";
                    date = "2008-03-12";
                    "event_status" = Missed;
                },
            );
        }
    );

在这个回复中,我们甚至不知道键“ObjectiveC”和“Java”。密钥(“ObjectiveC和Java”)应该在每次恢复的响应中改变。如何获取密钥值(未知密钥)?我如何解析这个响应并获得值?

2 个答案:

答案 0 :(得分:3)

NSDictionary有- (NSArray *)allKeys- (NSArray *)allValues。其中一个可能会有所帮助

NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"Key", @"Value", @"Key 2", @"Value 2", nil];
    NSArray *values = [lessonDict allValues];

    NSArray *keys = [lessonDict allKeys];
    NSLog(@"Keys: %@",keys);
    NSLog(@"Values: %@",values);

答案 1 :(得分:3)

我会通过键枚举来获取值。以下是objective-c中的枚举示例。

NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
    //assuming value will be string
    NSString *valueForKey = [myDictionary valueForKey:key]; 

    //assuming value is another dictionary
    NSDictionary *subDictionary = [myDictionary objectForKey:key];
}

如果您不知道子词典的键,您也可以通过这些键进行枚举。