Objective, object

Source: Internet
Author: User

Objective, object

Use of KVC

 

 

1. KVC full name key valued coding key-value Encoding

The reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known. For any object, any method and attribute of this class can be called. JAVA and C # both have this mechanism. There are also ObjC, so you can perform dynamic attribute read/write without any operation at the root, that is, KVC.

The KVC operation method is provided by NSKeyValueCoding, which is the NSObject class. That is to say, almost all objects in ObjC support KVC operations.

 

2. Common Methods

 

How to get the value

ValueForKey: Specifies the name of the NSString attribute.

ValueForKeyPath: Specifies the path of the NSString attribute, in the form of xx. xx.

ValueForUndefinedKey. Its default implementation is to throw an exception. You can rewrite this function for error handling.

 

The problem arises: there are now connected classes, Book classes (corresponding attributes: name, prices) and Person classes (corresponding attributes: name, height, Book * book ), person has a book named "descendant of the sun". How can I assign a value to this book through KVC?

My personal summary: because what I want to modify is not the attributes of the corresponding class or the Person class, but the attributes of the Book (person. book), I need to modify them through valueForKeyPath. ^_^

                               

 

Modification Method

SetValue: forKey:

SetValue: forKeyPath:

SetValue: forUndefinedKey:

 

SetValue: forKey search process:

Note:

1. When you use KVC to indirectly modify object attributes, the system automatically determines the object attribute type and completes the conversion.

2. KVC can access member variables, regardless of whether the getter/setter method is provided or whether the visibility is correct or not.

 SetValue: forUndefinedKey and valueForUndefinedKey

The main purpose of KVC is nothing more than ORM ing, that is, to convert a dictionary into a model. However, some fields returned by the server may be oc keywords such as 'id' and 'description. In the example of id given in the code above, the key value behind @ property cannot be id, so the value is replaced by an upper-case ID. KVC is case-sensitive and we don't have to worry about it. In this case, we only need to assign the key value of id to the key value of ID in setValue: forUndefinedKey to avoid the embarrassment of the keyword.

 

3. dict <-> model conversion

 

Dictionary-to-Model

[Self setValuesForKeysWithDictionary: dict];

 

Model conversion to Dictionary

[P dictionaryWithValuesForKeys: array];

 

4. KVC set

 

Both NSArray and NSSet support KVC.

[Array valueForKeyPath: @ "dog. name"];

 

5. Use KVC to calculate attributes

 

Format: [p valueForKeyPath: @ "Left keypath section. @ Collectionoperator section. Right keypath section"];

 

Left keypath part: the object path to be operated.

Collectionoperator part: Use the @ symbol to determine the set operation used.

Right keypath: The property of the set operation.

 

Example: [p valueForKeyPath: @ "books.@sum.price"];

 

@ Avg: Average Value

@ Count: Total

@ Max: Maximum

@ Min: Minimum

@ Sum: Total

 

6. Code and actual editing

1) When KVC is used to assign values to the object attributes, it is called when the corresponding Value is not found based on the input Key Value

1-(void) setValue :( id) value forUndefinedKey :( NSString *) key {2 3 NSLog (@ "key =%@ not found", key); 4 5}

 

2) When the corresponding key value is found, the code is

1 // 2 // main. m 3 // KVC familiar with and enhanced 4 // 5 // Created by ma c on 16/5/16. 6 // Copyright©In 2016, Peng shengyu. all rights reserved. 7 // 8 9 # import <Foundation/Foundation. h> 10 11 # import "Model. h "12 13 int main (int argc, const char * argv []) {14 @ autoreleasepool {15 16 Model * model = [[Model alloc] init]; 17 18 [model setValue: @ "Coder, PSS" forKey: @ "name"]; 19 [model setValue: @ "178" forKeyPath: @ "height"]; 20 21 // NSLog (@ "% @", model); 22 23 NSLog (@ "Name: % @, height: % @", [model valueForKey: @ "name"], [model valueForKey: @ "height"]); 24 25 26 27} 28 return 0; 29}

 

Result:

 

3) use the native method to parse data

Because I do not have a server, I write a false data (plist) for parsing, and the results are the same

(1) plist:

(2) parse data code

Model. m

 

1 // 2 // Model. h 3 // KVC familiar with and enhanced 4 // 5 // Created by ma c on 16/5/16. 6 // Copyright©In 2016, Peng shengyu. all rights reserved. 7 // 8 9 # import <Foundation/Foundation. h> 10 11 @ interface Model: NSObject12 13 @ property (nonatomic, copy, readonly) NSString * name; 14 15 @ property (nonatomic, assign, readonly) NSInteger height; 16 17 + (NSArray *) loadData; 18 19 @ end

Model. h

 

1 // 2 // Model. m 3 // KVC familiar with and enhanced 4 // 5 // Created by ma c on 16/5/16. 6 // Copyright©In 2016, Peng shengyu. all rights reserved. 7 // 8 9 # import "Model. h "10 11 @ implementation Model12 13-(NSString *) description14 {15 return [NSString stringWithFormat: @" model. name = % @, mdoel. height = % @ ", _ name, @ (_ height)]; 16} 17 18-(void) setValue :( id) value forUndefinedKey :( NSString *) key {19 20 NSLog (@ "key =%@ not found", key); 21 22} 23 24 + (NSArray *) loadData {25 26 // obtain the plist file path 27 NSString * path = @ "/Users/mac/Desktop/KVC familiarity and enhancement/CoderPSS. plist "; 28 29 // get the array 30 NSArray * array = [NSArray arrayWithContentsOfFile: path] In the plist file; 31 32 // initialize the variable array 33 NSMutableArray * dataList = [NSMutableArray array]; 34 35 // use the dictionary to traverse the array 36 in plist (NSDictionary * dict in array) {37 38 // initialize model class 39 Model * model = [[Model alloc] init]; 40 41 // use the KVC (setValuesForKeysWithDictionary) method to parse data 42 [model setValuesForKeysWithDictionary: dict]; 43 44 // Add the model class to the variable array 45 [dataList addObject: model]; 46} 47 48 // return the variable array 49 return dataList; 50} 51 52 @ end

Running result

 

 

Related Article

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.