Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"];
like image 721
Teo Avatar asked Apr 23 '13 07:04

Teo


People also ask

What is key-value coding in iOS?

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.

What is key-value coding in Swift?

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.

What is key-value Coding and key-value observing?

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.

What is KVC in iOS?

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.


1 Answers

The keyPath should fit you requirements.

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

Check doc NSKeyValueCoding Protocol and Key-Value Coding Fundamentals

like image 89
Andrea Avatar answered Sep 21 '22 21:09

Andrea