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"];
Key-value coding is a mechanism enabled by the NSKeyValueCoding informal protocol that objects adopt to provide indirect access to their properties. When an object is key-value coding compliant, its properties are addressable via string parameters through a concise, uniform messaging interface.
According to Apple: Key-value coding is a mechanism for accessing an object's properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.
KVO and KVC or Key-Value Observing and Key-Value Coding are mechanisms originally built and provided by Objective-C that allows us to locate and interact with the underlying properties of a class that inherits NSObject at runtime.
KVC locates an object's property through a key, which is a string identifier. A key usually corresponds to the name of an accessor method or instance variable defined by the object.
The keyPath
should fit you requirements.
[p setValue:@"234567" forKeyPath:@"address.zipcode"];
Check doc NSKeyValueCoding Protocol and Key-Value Coding Fundamentals
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With