Detailed explanation of the usage example of KVC in IOS
KVC is the abbreviation of Key Value Coding, which means key-value encoding. In iOS, a method is provided to access the property property method indirectly by using the name of the property (that is, the Key). Some of the difficult words are actually because we can see the various properties of the class through class definition. Then, using the name of the property, we can access the property value of the object instantiated by the class.
This method can access the object's properties without accessing the getter/setter method. Because if a member variable of a class does not provide a getter/setter, the outside world will lose access to this variable. KVC provides a way to access, which can be very powerful in some occasions.
Not much to say, the code:
@interface myPerson : NSObject { NSString *_name; int _age; int _height; int _weight; } @end
@interface testViewController : UIViewController @property (nonatomic, retain) myPerson *testPerson; @end
- (void)testKVC { testPerson = [[myPerson alloc] init]; NSLog(@"testPerson's init height = %@", [testPerson valueForKey:@"height"]); [testPerson setValue:[NSNumber numberWithInt:168] forKey:@"height"]; NSLog(@"testPerson's height = %@", [testPerson valueForKey:@"height"]); }
The first piece of code defines a myPerson class. This class has a _height attribute, but does not provide any getter/setter access methods. At the same time, there is a myPerson object pointer in the testViewController class.
When myPerson is instantiated, it is generally impossible to access the _height property of this object, but we did it through KVC, and the code is the testKVC function.
The print value after running is:
2013-11-02 11:16:21.970 test[408:c07] testPerson's init height = 0 2013-11-02 11:16:21.971 test[408:c07] testPerson's height = 168
This means that the _height attribute is indeed read and written.
Common methods of KVC:
- (id)valueForKey:(NSString *)key; - (void)setValue:(id)value forKey:(NSString *)key;
The valueForKey method reads the object's properties based on the value of the key. setValue:forKey: is to write the object's properties based on the value of the key.
Here are a few to emphasize
1. The value of the key must be correct. If the spelling is wrong, an exception will occur.
2. When the value of the key is not defined, valueForUndefinedKey: This method will be called. If you write this method yourself, the value of the key will be called here if it is wrong.
3. Because class keys are nested repeatedly, there is a concept of keyPath. KeyPath is to use . numbers to link keys one by one, so that you can access them according to this path.
4. NSArray/NSSet and others support KVC
The above is how to use IOS KVC. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!