IOS advanced development KVC (1)

Source: Internet
Author: User

IOS advanced development KVC (1)

The Skillful Use of KVC can bring us great benefits in the development process. Especially when the json conversion model is used, KVC frees programmers from tedious and nutritious code accumulation. Reducing the amount of code is to reduce the probability of errors. KVC is flexible to use. This flexibility is based on strict naming requirements. This naming requirement is actually a convention. In the world of programs, conventions play a much greater role than development itself. Good conventions can free programmers from many judgments and reduce errors. KVC has the following functions:

1) direct assignment

You can use KVC to assign values to an attribute of an object. Assume that we now have a Person class which contains two attributes: one is the read-only name attribute and the other is the age attribute of the Number type.

/// Person. h // KVC // Created by Deng Zhuli on 15-4-24. // Copyright (c) 2015 GiveMeFive. all rights reserved. // # import
 
  
@ Interface Person: NSObject @ property (nonatomic, copy, readonly) NSString * name; @ property (nonatomic, assign) NSNumber * age; @ end
 

When we define attributes, the system automatically generates the setter and getter methods for us. We can use the setter and getter methods, or read or write values. Of course, we can also use KVC to read and write data. Let's take a look at the code first, and then briefly discuss the issues that need attention.

# Import "ViewController. h "# import" Person. h "@ interface ViewController () @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; Person * person = [[Person alloc] init]; [person setValue: @ "25" forKey: @ "age"]; [person setValue: @ "maid" forKey: @ "name"]; NSLog (@ "the name of person is % @", person. name); NSLog (@ "the annual collar of person is % @", [person valueForKey: @ "age"]);} @ end

20:40:13. 286 KVC [6208: 218095] The Name of person is King pilaf

20:40:13. 287 KVC [6208: 218095] The annual collar of person is 25

If you have never been in touch with KVC, you may think: I wiped it, did the dawang's brain break down? How can I assign values to read-only attributes ?! In addition, the age attribute is clearly of the NSNumber type. How can I assign a string to it ?! Yes, that's what I want to say. KVC can not only assign values, but also damage the read-only feature. Of course, this is just a detail we need to pay attention to. More importantly, KVC has the function of automatic packing (automatic type conversion) and we do not need to convert the type. Since the data field in the development process is the world of strings, this automatic packing function is indeed excellent.

2) supports key-value path

What is a supported key-value path? To put it bluntly, nesting is supported. Assume that there is a book class that contains the name of the book. Books can be owned by persons (that is, they can be attributes of persons)

#import 
 
  @interface Book : NSObject@property(nonatomic,copy)NSString* name;@end
 

So we can use it like this.

Person * person = [[Person alloc] init]; Book * myBook = [[Book alloc] init]; person. book = myBook; [person setValue: @ "programmer's Guide to pancakes" forKeyPath: @ "book. name "]; NSLog (@" % @ ", [person valueForKeyPath: @" book. name "]);

The key here can be directly separated by location. Note: keyPath is used here. Of course, keyPath can also be used in "1) attribute assignment, however, if keyPath is not necessary, performance will be wasted. I have nothing to say here. I'm sorry for my first 5-cent electricity bill.

3) support operators

If we have 10 strings and want to find the total length of these 10 strings, we can use the operators provided by KVC.

NSArray * books = @ [@ "", @ "programmer's pancake Collection", @ ""]; NSLog (@ "% @", [books valueForKeyPath: @ "@ sum. length "]);

Here @ sum is provided by KVC, not written by us. There are five functions like this: @ avg, @ count, @ max, @ min, @ sum. We can use it directly. However, it is said that the efficiency is slower than the for loop. I have never tested it. If you are interested, test it.

4) Error Interception

For our front-end programmers, backend programmers are sometimes a troubleMaker. He always tells you something strange. For example, pass you an id attribute, or do not send anything to you. If there is such a json file {"id": "1 "}. This forces us to take id as an attribute of the data model !! Old man does not want! Even if it is used as an attribute, no error is reported. Yield? Or fight? This is a problem. Fortunately, our predecessors have given us the answer. If we have a Model class, the whoCare attribute in the class is the attribute that should have been named as id. We also wrote an initialization method for dictionary-to-model conversion.

@interface Model : NSObject@property(nonatomic,strong)id whoCare;-(instancetype)initWithDict:(NSDictionary *)dict;@end

Then we can rewrite the-(void) setValue :( id) value forUndefinedKey :( NSString *) key Method in the. m file. This method is called when the system cannot find the attribute with the same name when the dictionary is converted to the model. So we can intercept errors in this method and assign values so that no error is reported.

# Import "Model. h "@ implementation Model-(instancetype) initWithDict :( NSDictionary *) dict {if (self = [super init]) {// forgot to introduce the frequently used dictionary-to-model statements [self setValuesForKeysWithDictionary: dict];} return self ;}- (void) setValue :( id) value forUndefinedKey :( NSString *) key {if ([key isEqualToString: @ "id"]) {self. whoCare = value ;}@ end

After writing the model class, let's test it.

#import "Model.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    NSDictionary *dict=@{@"id":@"1"};        Model *model=[[Model alloc] initWithDict:dict];        NSLog(@"%@",model.whoCare);}@end

The program did not crash and the assignment was successful. Believe it or not, read the printed information.

21:12:00. 676 KVC [6393: 228807] 1

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.