Search code examples
ioscoding-stylekey-valuekvc

iOS key value coding


Let's assume we have an object of type person, which has a property called name.

Person *p;
[p setValue:@"John" forKey:@"name"];

This works very nicely. What I want to do is dig deeper. Say the class person has another property called address which is of class Address and has a field called zipcode.

Is there a simpler way of assigning the zipcode from the person than this? Maybe something cleaner and clearer?

[[p valueForKey:@"address"] setValue:@"234567" forKey:@"zipcode"];

Solution

  • The keyPath should fit you requirements.

    [p  setValue:@"234567" forKeyPath:@"address.zipcode"];
    

    Check doc NSKeyValueCoding Protocol and Key-Value Coding Fundamentals