IOS: KVC overview and usage

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.