KVC, that is, key-value coding, is a mechanism that uses string identifiers to indirectly Access Object Attributes. It is the basis of many technologies.
There are two main methods: setvalue: forkey, valueforkey
In programming guide, using KVC can simplify the code, but in fact, it depends on the specific situation.
Code example:
1. First define two datamodel. This datamodel definition cannot access attributes.
@interface BookData : NSObject { NSString * bookName; float price; AuthorData * author;}@end@implementation BookData@end
@interface AuthorData : NSObject { NSString * name;}@end@implementation AuthorData@end
2. Use KVC
BookData * book1 = [[BookData alloc] init];[book1 setValue:@"english" forKey:@"bookName"];[book1 setValue:@"20.0" forKey:@"price"];AuthorData * author1 = [[AuthorData alloc] init];[author1 setValue:@"tom" forKey:@"name"];[book1 setValue:author1 forKey:@"author"];NSLog(@"value=%@",[book1 valueForKey:@"bookName"]);NSLog(@"price=%f",[[book1 valueForKey:@"price"] floatValue]);NSLog(@"author=%@",[book1 valueForKeyPath:@"author.name"]);[book1 release];
3. Note: during use, the key value cannot be written incorrectly, that is, the attribute name cannot be written incorrectly, and it is case sensitive.
4. Back to the initial question, when should I use KVC?
As defined by datamodel above, from the programmer's perspective, I feel that it is not standard enough. At least we should ensure normal access, whether it is using the system's get/set method, or define your own interface (getbookprice, the name looks friendly ).
The official key-value observing Programming Guide contains some code to demonstrate how to simplify the code. If you are interested, you can check it out.
For your understanding of KVC, please advise.