Introduction to the

KVC (Key Value Coding) is a mechanism for accessing class attributes through keys. Instead of calling setters and getters. Properties of objects can be accessed and modified dynamically at run time. KVC method defined in the Foundation/NSKeyValueCoding.

Common methods are provided:

-(void)setValue:(id)value forKeyPath:(NSString *)keyPath;
-(void)setValue:(id)value forKey:(NSString *)key;
-(id)valueForKeyPath:(NSString *)keyPath;
-(id)valueForKey:(NSString *)key;
Copy the code

Use 1: If name is an attribute of the custom Person class, use KVC.

Person1 setValue:@"jack" forKey:@"name"]; NSString *name = [person1 valueForKey:@"name"];Copy the code

Using 2: forKeyPath is access to the more “deep” objects. An element of a group, an attribute of an object. Such as:

[myModel setValue:@"beijing" forKeyPath:@"address.city"]; NSArray *names = [array valueForKeyPath:@"name"];Copy the code

Both KVC and KVO belong to key-value programming, and the underlying implementation mechanism is ISA-Swizzing

The underlying principle

  • setValue:forKey:

1. Find the method in the order of setKey:, _setKey:, pass the parameter if found, and call the method. 2. If not found, check accessInstanceVariablesDirectly method return value, return the NO call the setValue: forUndefinedKey: and throw an exception NSUnknownKeyException.

Methods accessInstanceVariablesDirectly returned by default is YES

3. If YES is returned, look for member variables in the order of _key, _isKey, key, isKey, and assign values directly. 4. If you don’t find call setValue: forUndefinedKey: and throw an exception NSUnknownKeyException.


  • valueForKey:

1. Search for methods in the order of getKey, key, isKey, and _key, and directly call the methods if they are found. 2. If not found, check accessInstanceVariablesDirectly method return value, return NO call valueForUndefinedKey: and throw an exception NSUnknownKeyException. 3. If YES is returned, look for member variables in the order of _key, _isKey, key, and isKey. If you find it, you just value it. 4. If none is found, call valueForUndefinedKey: and throw NSUnknownKeyException.