使用 valueForKeyPath 获取特定数据


Printing description of self->data:
{
    root =     {
        participant =         (
                        {
                age =                 {
                    text = "n        27";
                };
                class =                 {
                    text = "n        M 25-29";
                };
                gender =                 {
                    text = "n        M";
                };
            },
                        {
                age =                 {
                    text = "n        27";
                };
                class =                 {
                    text = "n        M 25-29";
                };
                gender =                 {
                    text = "n        M";
                };
            },
                        {
                age =                 {
                    text = "n        29";
                };
                class =                 {
                    text = "n        M 25-29";
                };
                gender =                 {
                    text = "n        M";
                };
            },

有一个我的数据示例。真实记录是913个项目,由男性和女性参与者组成。如何将命令缩减为男性或女性?

我试过valueForKeyPath:@"root.participant.gender.text==M"但事实并非如此。我特别想知道男性和女性的class,以防有更好的方法。

您应该使用

[[self valueForKeyPath:@"root.participant.gender.text"] isEqualToString:@"n M"(引号不将整个表达式括起来,而是使用 -isEqualToString:(而不是 valueForKeyPath:@"root.participant.gender.text==M"

没有任何效果,所以我最终选择了这个

NSArray *participants = [self.data valueForKeyPath:@"root.participant"];
NSMutableArray *men = [[NSMutableArray alloc] init];
NSMutableArray *women = [[NSMutableArray alloc] init];
for(NSDictionary *p in participants) {
    NSString *t = [XMLReader cleanString:[p valueForKeyPath:@"chiptime.text"]];
    NSNumber *m = [NSNumber numberWithFloat:[self timeToMinutes:t]];
    if([[XMLReader cleanString:[p valueForKeyPath:@"gender.text"]] isEqualToString:@"M"]) {
        [men addObject:m];
    } else {
        [women addObject:m];
    }
}

XMLReader cleanString只是倒掉ns*垃圾。

最新更新