Using setValuesForKeysWithDictionary with child objects and JSON
I have a json string
{"name":"test","bar":{"name":"testBar"}}
In objective c I have an object
@interface Foo : NSObject {
}
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Bar * bar;
@end
And I just synthesize those properties. And I have a child object with synthesized properties.
@interface Bar : NSObject {
}
@property (nonatomic, retain) NSString * name;
@end
Then here is the code where I'm trying to get into the Foo object where response is the json string above:
SBJsonParser *json = [[SBJsonParser new] autorelease];
parsedResponse = [json objectWithS开发者_开发百科tring:response error:&error];
Foo * obj = [[Foo new] autorelease];
[obj setValuesForKeysWithDictionary:parsedResponse];
NSLog(@"bar name %@", obj.bar.name);
This throws an exception on the NSLog statement of:
-[__NSCFDictionary name]: unrecognized selector sent to instance 0x692ed70'
But if I change the code to it works:
NSLog(@"bar name %@", [obj.bar valueForKey:@"name"]);
I'm confused at why I can't do the first example, or am I doing something wrong?
Have you tried this?
// Foo class
-(void)setBar:(id)bar
{
if ([bar class] == [NSDictionary class]) {
_bar = [Bar new];
[_bar setValuesForKeysWithDictionary:bar];
}
else
{
_bar = bar;
}
}
-setValuesForKeysWithDictionary:
isn't smart enough to recognize that the value of the key "bar" should be an instance of Bar
. It's assigning an NSDictionary
to that property. Thus, when you ask for the property "name," the dictionary can't field that request. However, an NSDictionary
does know how to handle -valueForKey:
, so it happens to work in that case.
So you need to use something smarter than -setValuesForKeysWithDictionary:
to populate your objects.
精彩评论