KVC mechanism and KVC Mechanism
KVC Mechanism
KVC is a big move in cocoa to indirectly obtain or modify object attributes.
I. Role of KVC:
One of KVC's major moves:
[SelfsetValuesForKeysWithDictionary: dict];
KVC's two major moves:
When using KVC to obtain a value, if the specified object does not contain the "key name" of the keyPath, it will automatically enter the internal search of the object
If the value object is an array, an array is also returned.
[Self. carGroups valueForKey: @ "title"]; // It will be searched in the nested plist file in sequence.
Kvc mechanism considerations:
1. assign values to the model based on the dictionary. It is too troublesome to assign values to the model based on key-value pairs. KVC is used to assign values to the model, note that if the attribute in the model does not match the key in the dictionary, an error is returned. The model attribute is not found.
2. Not all attributes in the model can appear in the plist file.
Ii. Use of KVC 1. KVC can change private variables. 2. KVC supports mathematical operations.
3. forKeyPath includes the forKey function. 4. The. operator can be used in forKeyPath to find the attributes of an object layer by layer. 5. If an attribute of the forKeyPath lookup object is of the array type, a new array is returned. 6. assign a value to [selfsetValue: tabBarforKeyPath: @ "tabBar"];
7. Set the value to [selfvalueForKeyPath: @ "tabBar"].
Iii. Internal implementation principle of KVC internal implementation principle of KVC: Using KVC to assign values to model attributes (setValuesForKeysWithDictionary): all key-value pairs in the dictionary are traversed, call the setValue: forKey of the model object and assign values to the model attributes based on all the keys in the dictionary. However, when the attributes in the model do not match those in the dictionary, when the model calls setValue: forKey and the attributes in the model are not found based on the key, an error is reported.
Solution: Use the runtime mechanism to locate the key-value pairs in the dictionary based on the attributes in the model and assign values to the attributes. In this way, the error that the corresponding key cannot be found will not be reported.