KVC Analysis and examples

Source: Internet
Author: User

KVC and KVO are the key concepts of Objective C, something that the individual believes must be understood, and the following is an example explanation.

Key-value Coding (KVC)

KVC, which means nskeyvaluecoding, an informal Protocol, provides a mechanism to indirectly access the properties of an object. KVO is one of the key technologies based on KVC implementation.

An object has some properties. For example, a person object has a name and an address property. In KVC parlance, the person object has a value corresponding to the key of his name and address. A key is just a string, and its corresponding value can be any type of object. At the most basic level, KVC has two methods: one is to set the value of key and the other is to get the value of key. As in the following example:

1 voidChangeName (Person *p, NSString *newName)2 {3  4     //using the KVC accessor (getter) method5NSString *originalname = [P Valueforkey:@"name"];6  7     //using the KVC accessor (setter) method.8[P setvalue:newname Forkey:@"name"];9  TenNSLog (@"Changed%@ ' s name to:%@", Originalname, newName); One   A}

Now, if person has another key spouse (spouse), spouse's key value is another person object, which can be written in KVC:

1 voidLogmarriage (Person *p)2 {3  4     //just using the accessor again, same as example above5NSString *personsname = [P Valueforkey:@"name"];6  7     //This was different, because it is using8     //a "key path" instead of a normal "key"9NSString *spousesname = [P Valueforkeypath:@"Spouse.name"];Ten   OneNSLog (@"%@ is happily married to%@", Personsname, spousesname); A   -}

Key and key Pat to distinguish, key can get the value from an object, and key path can be more than one key with the dot "." Split, such as:

[p valueForKeyPath:@"spouse.name"];

The equivalent of this ...

[[p valueForKey:@"spouse"] valueForKey:@"name"];

Explanation about KVO See: http://www.cnblogs.com/cy568searchx/p/5668263.html KVO mechanism analysis and demonstration

KVC Analysis and examples

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.