IOS SDK Detailed KVC

Source: Internet
Author: User
Tags scalar

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

Introduction: The structure of this article
Definition of KVC
Several scenes of KVC

Hope, through this article to let not understand KVC students get started, KVC in the development of iOS is a more important concept, but also understand KVO Foundation.

the definition of a KVC
The full name of the KVC is Key-value coding, which accesses the property by Key-value Way. In many places, KVC is very convenient.
Property

@property (strong,nonatomicNSString * message;

Assign value

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

Take value

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

In addition to the object can be used KVC, the scalar can also be used KVC, because the foundation of the scalar KVC internal conversion.
For example

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

All of the above are VALUEFORKEY,KVC also support Valueforkeypath, where path is a string path, separated by points, layered in depth.
For example

Therefore, Valueforkeypath is easy for complex collection class handling and for complex property access.
For example

 Nsarray * array  = @[@{@ "key" : @{@ "1" : @ "2"  },@ "Key2" : @ "value2" }, @{@ "key" : @{@ "1" : @ "3" }, @ "Key2" : @ "value2" }, @{@ "key" : @{@ "1" : @ "4" },@<    Span class= "hljs-string" > "Key2" : @ "value2" }]; NSLog (@ "%@" , [array  Valueforkeypath:@ "key.1" ]);  

A brief explanation of the process
Each object is valueforkey:@ "key", and then the returned array is
[Email protected] "1"

Typical use scenarios for two KVC

2.1 Model and view synchronization middleware.
I wrote a simple demo.
Effect

Each time you click Create, a random number of 100 is generated, and then several labels display the corresponding statistics.

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[NSStringstringwithformat:@"@%@.self", key];} -(UILabel*) Labelforkey: (NSString*) key{return[ SelfValueforkey:key];} -(void) updateaggregationlabels{ for(NSString* Key in Self. Stringkeys) {UILabel* label = [ SelfLabelforkey:key];NSNumber* Aggregation = [ Self. Numarrayvalueforkeypath:[ SelfAggregationkeypath:key]]; Label. Text= [NSStringstringwithformat:@"%@:%.1f", key,aggregation. Doublevalue]; }}- (ibaction) Createtenrandomnumbers: (ID) Sender {[ Self. NumarrayRemoveallobjects];NSString* String = @""; for(inti =0; I <Ten; i++) {intnum = arc4random ()% -; [ Self. Numarrayaddobject:@ (num)]; string = [NSStringstringwithformat:@"%@%d", String,num]; } Self. Numbers. Text= string; [ SelfUpdateaggregationlabels];}

Here, the property is accessed in a KVC way.

有些同学不禁会问,我干嘛不直接在这个target-action中直接响应。这么写主要是为了方便以后维护。例如,假如我要新加上一个label叫做count,以上的代码中,我只需要修改一个函数,就是为-(NSArray *)stringKeys{    return @[@"min",@"max",@"avg"];}这个数组添加一个新的key。一个简单的例子,抛砖引玉,主要是尽量解耦合的思想,这个很重要。

2.2 KVC integrates several sets of operators, which is very convenient to use, and the code execution efficiency is very high.
The expression of the set operator is the double quotation mark in the keypath that appears @
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 a collection

Basic set operators are divided into several

@count@max@min@avg@sum

To better explain, 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, for example
Initializes an array of user.

-(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 the 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     返回keyPath的结果,重复信息不过滤@distinucUnionOfObjects  重复信息过滤

For example

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

Output

2015-02-12 21:12:38.513 kvckvodemo[501:11415] (
100,
150,
80,
80
)
2015-02-12 21:12:38.514 kvckvodemo[501:11415] (
150,
80,
100
)

Some error handling of 2.3 KVC
scalar cannot be nil
For example

@property (nonatomicint number;

And then

setforKey:@"number"];

If you do not do error handling, the program crashes

用这个函数进行想要的错误处理-(void)setValue:(id)value forUndefinedKey:(NSString *)key{    NSLog(@"undfined key");}

Unrecognized key handling

 [selfsetValue:nilforKey:@"dsag"]; [selfvalueForKey:@"123124"];

Randomly entered two key, if not error handling, the program will crash.
Use these two functions to handle the unrecognized key, as for how to handle it, depending on the situation.

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

Of course, with the message forwarding technique, the next step in error handling is to handle the error. This involves the iOS runtime content, involving too much, not in the scope of this article. However, don't let the error pass too long, deal with it in time, always right.

IOS SDK Detailed KVC

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.