KVC and KVO are the key concepts of Objective C, something that the individual believes must be understood, and the following is an example explanation.
Key-value Coding (KVC)
KVC, which means nskeyvaluecoding, an informal Protocol, provides a mechanism to indirectly access the properties of an object. KVO is one of the key technologies based on KVC implementation.
An object has some properties. For example, a person object has a name and an address property. In KVC parlance, the person object has a value corresponding to the key of his name and address. A key is just a string, and its corresponding value can be any type of object. At the most basic level, KVC has two methods: one is to set the value of key and the other is to get the value of key. As in the following example:
1 voidChangeName (Person *p, NSString *newName)2 {3 4 //using the KVC accessor (getter) method5NSString *originalname = [P Valueforkey:@"name"];6 7 //using the KVC accessor (setter) method.8[P setvalue:newname Forkey:@"name"];9 TenNSLog (@"Changed%@ ' s name to:%@", Originalname, newName); One A}
Now, if person has another key spouse (spouse), spouse's key value is another person object, which can be written in KVC:
1 voidLogmarriage (Person *p)2 {3 4 //just using the accessor again, same as example above5NSString *personsname = [P Valueforkey:@"name"];6 7 //This was different, because it is using8 //a "key path" instead of a normal "key"9NSString *spousesname = [P Valueforkeypath:@"Spouse.name"];Ten OneNSLog (@"%@ is happily married to%@", Personsname, spousesname); A -}
Key and key Pat to distinguish, key can get the value from an object, and key path can be more than one key with the dot "." Split, such as:
[p valueForKeyPath:@ "spouse.name" ]; |
The equivalent of this ...
[[p valueForKey:@ "spouse" ] valueForKey:@ "name" ]; |
Explanation about KVO See: http://www.cnblogs.com/cy568searchx/p/5668263.html KVO mechanism analysis and demonstration
KVC Analysis and examples