reference

Ke.qq.com/course/3145…

KVC

KVC, commonly known as “key-value encoding,” allows access to a property through a key.

-(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

The difference between key and key path

ForKey can only assign values to attributes of the current object.

ForKeyPath can assign values to properties of properties of an object.

ForKeyPath is recommended.

ValueForKey and valueForKey path

ValueForKey can only get the value of the current object attribute.

ValueForKeyPath can get the value of the property of the current object property.

ValueForKeyPath is recommended.

The underlying implementation of KVC assignment

1. Search for the set method in the sequence of setKey and _setKey.

2. If you cannot find the set method, call accessinstancevariablesdirectly get return values.

3. Return YES and assign values to the member variables in the _key,_isKey,key, and isKey order.

4. Return NO and throw Nsunknownkevexception.

5. If none of the four member variables can be found, Nsunknownkevexception is thrown.

The underlying implementation of KVC value

1. Find the get method values in the order of getKey,key,isKey, and _key.

2. If you can’t find the above four the get method, call accessinstancevariablesdirectly get return values.

3. Return YES to find the values of the member variables in _key,_isKey,key, and isKey order.

4. Return NO and throw Nsunknownkevexception.

5. If none of the four member variables can be found, Nsunknownkevexception is thrown.

supplement

1. Accessinstancevariablesdirectly method returns whether to allow access member variables, the default returns YES.

The 2.@property decorated member variable automatically generates the corresponding getter and setter methods.

3. Modifying a property via KVC triggers KVO because the willChangeValueForKey and didChangeValueForKey methods are called internally by KVC.

4. If this article violates privacy or other things, please contact me, I will rectify or delete in the first time.