Objective-C (VII. KVC key-value encoding and instance description)-iOS development basics, objective-ckvc

Source: Internet
Author: User

Objective-C (VII. KVC key-value encoding and instance description)-iOS development basics, objective-ckvc

Combine the previous study notes and refer to Objective-C programming full solution (Third edition) To summarize Objective-C knowledge points. Knowledge points keep changing, just for reference,Take the official documents of Apple as standard~

VII. Key-value encoding KVC

The knowledge points of KVC are described in the following example:

Person. h file. The Person class has two member variables: name and age.

 @interface Person : NSObject {     @private     NSString *_name;     NSInteger _age; } - (void)setAge:(NSInteger)age; @end

Person. m implements this method

 @implementation Person - (NSString *)description {     return [NSString stringWithFormat:@"name:%@,age=%li", _name, _age]; } - (void)setAge:(NSInteger)age {     _age = age; } @end

Main. m

Person * p = [[Person alloc] init]; // p-> _ name = @ "Zane"; Inaccessible // 1. use KVC to set the private attribute value [p setValue: @ "Zane" forKey: @ "name"]; // 2. obtain the attribute value NSString * name = [p valueForKey: @ "_ name"] Through KVC; NSLog (@ "% @", name); [p setValue: @ 21 forKey: @ "age"]; NSLog (@ "% @", p );

Output:

2015-07-09 17:29:43.477 exercise_KVC[579:24344] Zane2015-07-09 17:29:43.478 exercise_KVC[579:24344] name:Zane,age=21

1. key-value coding: Used as the key value to indirectly access the information contained in the object.

Basically,As long as there are accessors, declared attributes, or instance variables, you can use their names as strings to access. (This variable can be accessed even if it is @ private)

2. Set the property value:

-(Void) setValue :( id) value forKey :( NSString *) key; // memory management performed [p setValue: @ "Zane" forKey: @ "name"];

A. if the name is incorrectly written and written as nama, nam1e, and so on, the compiler will not report an error, but will cause the running to crash.
B,Value is of the id type. Therefore, if it is of the basic data type, it needs to be packaged.

Get Attribute Value

 - (id)valueForKey:(NSString *)key; NSString *name = [p valueForKey:@"_name"];

If a Person also owns a dog and adds it to Person. h In @ class mode, the dog has the dogName attribute.You can specify the path settings.

[p setValue:@"wangwang" forKeyPath:@"dog._dogname"];NSLog(@"%@",[p valueForKeyPath:@"dog._dogname"])
- (id)valueForKeyPath:(NSString *)keyPath;- (void)setValue:(id)value forKeyPath:(NSString *)keyPath;

3. Disadvantages
(1)Destroys object-oriented Encapsulation;
(2) The Compiler does not check the configured keyValue for errors;
(3) The string needs to be parsed first, and the execution efficiency is lower than the set and get methods.

4. Other Instructions
(1) Use KVC to set attributes,Check whether the set method exists in the current class first.If the set method is used, the property settings are found if none exist.
To call the API, you can only write age, not _ age.
For example

[p setValue:@21 forKey:@"age"];[p setValue:@21 forKey:@"_age"];

You can set a breakpoint at the set method implementation of age. You will find that if _ age is written, the set method is not called.

(2) one-to-many relationship
Generally, it is first packaged into NSArray, and then assigned a value using the setValue method.
Access valueForKeyPath through the path during access

(3) Numerical Calculation
In the above example, the book member variable is added for the Person;
And Dog. h has the member variable dogage.

@ Interface Dog: NSObject {int _ dogage;}-(instancetype) initWithAge :( int) age; // and implement @ end

Main. m

Dog * dog1 = [[Dog alloc] initWithAge: 20]; Dog * dog2 = [[Dog alloc] initWithAge: 30]; Dog * dog3 = [[Dog alloc] initWithAge: 10]; NSArray * array = [NSArray arrayWithObjects: dog1, dog2, dog3, nil]; [p setValue: array forKey: @ "dog"]; // NSLog (@ "% @", [p valueForKeyPath: @ "dog. @ count "]); // Number of dogs NSLog (@" % @ ", [p valueForKeyPath: @" dog. @ sum. _ dogage "]); // NSLog (@" % @ ", [p valueForKeyPath: @" dog. @ avg. _ dogage "]); // average NSLog (@" % @ ", [p valueForKeyPath: @" dog. @ min. _ dogage "]); // minimum NSLog (@" % @ ", [p valueForKeyPath: @" dog. @ max. _ dogage "]); // maximum value

Output:

2015-07-09 17:29:43.479 exercise_KVC[579:24344] 32015-07-09 17:29:43.479 exercise_KVC[579:24344] 602015-07-09 17:29:43.480 exercise_KVC[579:24344] 202015-07-09 17:29:43.480 exercise_KVC[579:24344] 102015-07-09 17:29:43.480 exercise_KVC[579:24344] 30

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.