通过NSDictionary循环并添加到NSMutableArray

时间:2011-10-27 00:31:41

标签: objective-c nsmutablearray nsarray nsdictionary

我如何循环使用以下NSDictionary

2011-10-27 11:40:23.775 Discounts[305:f803] {
    NewDataSet =     {
        Discounts =         (
                        {
                BIN =                 {
                    text = "\n    900020";
                };
                DiscountId =                 {
                    text = "\n  \n    d06dab1b-a2a3-464e-a522-00185fcf5e7c";
                };
                DiscountPrice =                 {
                    text = "\n    75%";
                };
                GRP =                 {
                    text = "\n    8013230";
                };
                PCN =                 {
                    text = "\n    CLAIMNE";
                };
                Title =                 {
                    text = "\n    duralclon";
                };
                UID =                 {
                    text = "\n    100000";
                };
                text = "\n  ";
            },
                        {
                BIN =                 {
                    text = "\n    900020";
                };
                DiscountId =                 {
                    text = "\n  \n    159d9ba9-462c-47a2-a23e-002137c6fd2e";
                };
                DiscountPrice =                 {
                    text = "\n    75%";
                };
                GRP =                 {
                    text = "\n    8013230";
                };
                PCN =                 {
                    text = "\n    CLAIMNE";
                };
                Title =                 {
                    text = "\n    allermax";
                };
                UID =                 {
                    text = "\n    100001";
                };
                text = "\n  ";
            },
...

我试过了:

for (id key in discountsDict) {
  MyObject *obj = [[MyObject alloc] init];
  obj.Title = (NSString *)[key objectForKey:@"Title"]; // *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x6ca2eb0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Title.'
  [self.discounts addObject:obj];
  [obj release];
}

我不确定是否要创建包含内容的NSArray,然后循环显示该内容,以便将MyObject添加到NSMutableArray self.discounts {{1}}

提前致谢。

2 个答案:

答案 0 :(得分:-1)

您确实意识到该字典中只有一个元素(“NewDataSet”),对吧?

答案 1 :(得分:-2)

您要求key objectForKey:@"Title"key只是NSString*。你的真正含义是[[discountsDict objectForKey:key] objectForKey:@"Title"]。或者,如果您支持4.0及更高版本,则可以使用

[discountsDict enumerateKeysAndObjectsUsingBlock:^(id key, id val, BOOL *stop){
    MyObject *obj = [[MyObject alloc] init];
    obj.Title = [val objectForKey:@"Title"];
    [self.discounts addObject:obj];
    [obj release];
}];