KVC and iossdkkvc

Source: Internet
Author: User

KVC and iossdkkvc

Original Blog, reprinted, please indicate the source
Blog.csdn.net/hello_hwc

Architecture of this Article
KVC Definition
KVC scenarios

I hope that this article will help KVC beginners who do not understand KVC. KVC is an important concept in IOS development and is also the basis for understanding KVO.

Definition of a KVC
The full name of KVC is key-value coding, which allows you to access attributes in key-value mode. In many places, KVC is very convenient.
Attribute

@property (strong,nonatomic) NSString * message;

Assignment

 [self setValue:@"blog.csdn.net/hello_hwc" forKey:@"message"];

Value

 NSString * message =   [self valueForKey:@"message"];

In addition to KVC, KVC can be used for Scalar objects, because Foundation internally converts the scalar KVC.
For example

@property (nonatomic) int number;
[self setValue:@(10) forKey:@"number"];NSNumber *  num = [self valueForKey:@"number"];

All of the above are about valueForKey, and KVC also supports valueForKeyPath. Here, the path is a string path separated by vertices and goes deeper layer by layer.
For example

Therefore, valueForKeyPath is simple for complex collection class processing and complex attribute access.
For example

    NSArray * array = @[@{@"key":@{@"1":@"2"},@"key2":@"value2"},                        @{@"key":@{@"1":@"3"},@"key2":@"value2"},                        @{@"key":@{@"1":@"4"},@"key2":@"value2"}                        ];    NSLog(@"%@",[array valueForKeyPath:@"key.1"]);

Briefly describe this process
ValueForKey: @ "key" for each object, and then
ValueForKey @ "1"

Typical use cases of KVC

2.1 middleware for synchronization between Model and View.
I wrote a simple Demo.
Effect

Each time you click Create, a random number of less than 100 will be generated, and several labels will display the corresponding statistics respectively.

The core here is the synchronization of model and view.

Use the following code to implement

-(NSArray *)stringKeys{    return @[@"min",@"max",@"avg"];}-(NSString *)aggregationKeypath:(NSString *)key{    return [NSString stringWithFormat:@"@%@.self",key];}-(UILabel *)labelForKey:(NSString *)key{    return [self valueForKey:key];}-(void)updateAggregationLabels{   for (NSString * key in self.stringKeys) {        UILabel * label = [self labelForKey:key];        NSNumber * aggregation = [self.numArray valueForKeyPath:[self aggregationKeypath:key]];        label.text = [NSString stringWithFormat:@"%@: %.1f",key,aggregation.doubleValue];    }}- (IBAction)createTenRandomNumbers:(id)sender {    [self.numArray removeAllObjects];    NSString * string = @"";    for (int i = 0; i < 10; i++) {        int num = arc4random()%100;        [self.numArray addObject:@(num)];        string = [NSString stringWithFormat:@"%@ %d",string,num];    }    self.numbers.text = string;    [self updateAggregationLabels];}

Here, you can use KVC to access attributes.

Some may ask why I did not directly respond to this target-action. This is mainly written to facilitate future maintenance. For example, if I want to add a new label called count, in the above code, I only need to modify a function, that is,-(NSArray *) stringKeys {return @ [@ "min", @ "max", @ "avg"];} adds a new key to the array. For a simple example, it is very important to try to solve the coupling idea.

2.2 KVC integrates several set operators, which are very convenient to use and highly efficient in code execution.
The expression of the set operator is that @ appears in double quotation marks in keyPath @
For example

@"@min.count"

2.2.1 set operators are divided into several types:

  • Simple set operator: returns string, number, date
  • Object OPERATOR: returns an array.
  • Array and set operators: returns an array or set.

Basic set operators are divided into several types

@count @max@min@avg@sum

For better explanation, write a model class

@interface User : NSObject@property (strong,nonatomic)NSString * name;@property (nonatomic) NSUInteger accessTimes;-(instancetype)initWithName:(NSString *)name Count:(NSUInteger) times;@end

Then, give an example
Initializes an array of users.

-(NSMutableArray *)users{    if (!(_users)) {        _users = [[NSMutableArray alloc] init];        [_users addObject:[[User alloc] initWithName:@"jack" Count:100]];        [_users addObject:[[User alloc] initWithName:@"lucy" Count:150]];        [_users addObject:[[User alloc] initWithName:@"tom" Count:80]];        [_users addObject:[[User alloc] initWithName:@"lily" Count:80]];    }    return _users;}

Then, access data in the form of KVC

NSArray * names = [self.users valueForKeyPath:@"name"];    NSArray * counts = [self.users valueForKeyPath:@"accessTimes"];    NSNumber * avg = [self.users valueForKeyPath:@"@avg.accessTimes"];

2.2.2 object Operators

@ UnionOfObjects: The keyPath result is returned. duplicate information is not filtered. @ distinucUnionOfObjects duplicate information is filtered.

For example

 NSArray * time1 = [self.users valueForKeyPath:@"@unionOfObjects.accessTimes"];    NSArray * time2 = [self.users valueForKeyPath:@"@distinctUnionOfObjects.accessTimes"];    NSLog(@"%@",time1.description);    NSLog(@"%@",time2.description);

Output

21:12:38. 513 KvcKvoDemo [501: 11415] (
100,
150,
80,
80
)
21:12:38. 514 KvcKvoDemo [501: 11415] (
150,
80,
100
)

2.3 KVC error handling
The scalar cannot be nil.
For example

@property (nonatomic) int number;

Then

[self setValue:nil forKey:@"number"];

If no error is processed, the program will crash.

Use this function to handle the expected error-(void) setValue :( id) value forUndefinedKey :( NSString *) key {NSLog (@ "undfined key ");}

Unrecognized key Processing

 [self setValue:nil forKey:@"dsag"]; [self valueForKey:@"123124"];

If two keys are randomly entered without error processing, the program will crash.
These two functions are used to deal with unrecognized keys. As for how to deal with them, it depends on the situation.

-(void)setValue:(id)value forUndefinedKey:(NSString *)key{    NSLog(@"set undfined key");}-(id)valueForUndefinedKey:(NSString *)key{    NSLog(@"get undfined key");    return nil;}

Of course, the message forwarding technology can also be used to handle errors in the next step of error processing. This involves IOS runtime too much, which is beyond the scope of this article. However, do not let the error be transmitted for too long and be handled in time. This is always true.

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.