所以我有一个 NSDictionary ,其中一个键是字典数组。我映射到的类具有匹配的键名和设置器。setValuesForKeysWithDictionary 可以为我填写子词典吗?当我尝试它时,它似乎用指针垃圾或其他东西填充了对象,但我是一个新手,所以也许我做错了什么。那个功能是这样工作的吗?
1 回答
I realized that there was no way for setValuesForKeysWithDictionary to know what kind of object to fill the NSMutableArray with. I ended up making a custom setter for the array property that manually loops the elements of the array (of NSDictionaries) you pass in and calls setValuesForKeysWithDictionary for each one.
Here's the code:
There is a property called itemList of type NSMutableArray that I want filled it objects of type Item. The setItemList setter loops through the array of mystery objects, converting each NSDictionary to my Item type and adds them to a new array. Any comments on how to simplify the code would be welcome.
I also want to add some logic here to handle a situation where the array already contains Item objects instead of dictionaries. In actionscript you can check for null after you try to cast something to see if it worked, not sure what the equivalent process would be here. [item isMemberOfClass [Item class]]
always evaluates to YES, even if item is an NSDictionary. I can't understand why...
- (void) setItemList:(NSMutableArray*)input{
[itemList autorelease];
itemList = [[NSMutableArray alloc] initWithCapacity:input.count];
//loop through the array, creating an Item for for each object in the array
for(int i=0;i<input.count;i++){
Item* item = [Item new];
[item setValuesForKeysWithDictionary:(NSDictionary*)[input objectAtIndex:i]];
[itemList insertObject:item atIndex:i];
}
}
- (NSMutableArray*) itemList{
return itemList;
}