2011-10-27 74 views
0

我將如何循環以下NSDictionary通過NSDictionary循環並添加到NSMutableArray

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與內容,然後循環,以增加MyObjectself.discountsNSMutableArray

在此先感謝。

+0

你會得到什麼錯誤? – Dani

+0

@Danie:將錯誤添加爲引發錯誤的行旁邊的註釋。 – fuzz

+0

你可以轉儲字典在目標c風格,'NSLog(@「%@」,discountsDict)'併發布它? – Dani

回答

-2

您在詢問keyobjectForKey:@"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]; 
}]; 
+0

我的目標框架是4.0,我在Xcode 4.2上,我得到以下警告:'//實例方法enumerateObjectsAndKeysUsingBlock找不到' – fuzz

+0

此外:'NSString * title =(NSString *)[[discountsDict objectForKey:key] objectForKey: @「標題」];'也沒有工作。它爲'Title'返回'nil'。 – fuzz

+0

修正了,它實際上是:'enumerateKeysAndObjectsUsingBlock'而不是'enumerateObjectsAndKeysUsingBlock'。警告停止,但仍有'Title'返回'null'。 – fuzz

-1

你一定要明白,有隻有一個元素(「NewDataSet」)是該字典,對嗎?

+0

是的,你意識到你已經添加了這個答案而不是評論,對吧? – fuzz

相關問題