Key-Value encoding (KVC) is a common protocol used to obtain and set values for cocoa. In programming, the term "generic" is used to describe an implementation that can be applied to different contexts. Common code can reduce the amount of code in a project and allow the software to handle scenarios that programmers cannot predict. Cocoa has always attached great importance to universal, reusable code.
The KVC version looks like it needs more code input. Let me choose a scene that more embodies KVC value.
First, we define a class:
@interface Cdcperson:nsobject
{
NSString * FIRSTNAME;
NSString * LASTNAME;
NSNumber * PhoneNumber;
NSString * EmailAddress;
}
-(void) Setfirstname: (NSString *) value;
-(void) Setlastname: (NSString *) value;
-(void) Setphonenumber: (NSNumber *) value;
-(void) Setemailaddress: (NSString *) value;
@end
Some of the actual usage code is as follows:
Suppose inputvalues contains the key values that we want to set to the person
Nsdictionary *inputvalues;
Cdcperson *person = [[Cdcperson alloc] init];
Nsenumerator *e = [Inputvalues keyenumerator];
ID Dictkey, Dictvalue;
while (Dictkey = [E Nextobject])
{
Dictvalue = [Inputvalues Valueforkey:dictkey];
[Person Setvalue:dictvalue Forkey:dictkey];
}
The code snippet is generic, meaning that we don't need to change the code every time the person class adds a new instance variable.
But it can be better! Here is a simplified version of the above code:
Suppose inputvalues contains the key values that we want to set to the person
Nsdictionary *inputvalues;
Cdcperson *person = [[Cdcperson alloc] init];
[Person setvaluesforkeyswithdictionary:inputvalues];
Is it subtle? Here's an explanation of Apple's-setvaluesforkeyswithdictionary: implementation mechanism:
Sets the property value of a message receiver by key-value pairs, which are used to identify individual attributes. The default implementation is to call Setvalue:forkey for each key-value pair: Replace nil with a Nsnull value for the key-value pair.
In other words, this is no different from the first example. But-setvalue:forkey: What exactly did it do? This is where KVC's magic lies. It will actually find-setfirstname:,-setlastname:, Setphonenumber: And-setemailaddress: The implementations and invoke them. If these cannot be found, KVC will try several possibilities until the value is eventually set to the instance variable.
Key-value coding and general programming