Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 objectWithString: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?

like image 878
Tavis Bones Avatar asked Jun 09 '11 20:06

Tavis Bones


1 Answers

Have you tried this?

// Foo class

-(void)setBar:(id)bar
{
    if ([bar class] == [NSDictionary class]) {
        _bar = [Bar new];
        [_bar setValuesForKeysWithDictionary:bar];
    }
    else
    {
        _bar = bar;
    }
}
like image 186
Tuan Nguyen Avatar answered Oct 02 '22 14:10

Tuan Nguyen