美文网首页
valueForKeyPath

valueForKeyPath

作者: honzon_0 | 来源:发表于2017-03-29 18:45 被阅读100次

数据操作

确保操作的属性为数字类型,否则运行时刻错误。

NSArray *numArray = @[@-108,@1, @20, @33, @45, @59];
NSLog(@"%@",[numArray valueForKeyPath:@"@sum.self"]);
// -> 50
NSLog(@"%@",[numArray valueForKeyPath:@"@avg.self"]);
// -> 8.3333...
NSLog(@"%@",[numArray valueForKeyPath:@"@max.self"]);
// -> 59
NSLog(@"%@",[numArray valueForKeyPath:@"@min.self"]);
// -> -108

对象操作

首先自定义一个测试类Honzon

@interface Honzon : NSObject

@property (nonatomic ,copy)NSString *name;

- (NSString *)test;
- (void)testLog;
@end

@implementation Honzon

- (NSString *)test {
    return @"test";
}

- (void)testLog {
    NSLog(@"testLog");
}

- (void)testLogForKeyPath:(NSString *)keyPath {
    NSLog(@"%@",keyPath);
}

@end

然后分别将test,testLogtestLogForKeyPath传入valueForKeyvalueForKeyPath

NSLog(@"%@",[honzon valueForKey:@"test"]);//调用方法
// -> @"test"
NSLog(@"%@", [honzon valueForKeyPath:@"test"]);//调用方法
// -> @"test"

NSLog(@"%@", [honzon valueForKey:@"testLog"]);//调用方法
// -> @"testLog"
// -> @"(null)"
NSLog(@"%@", [honzon valueForKeyPath:@"testLog"]);//调用方法
// -> @"testLog"
// -> @"(null)"

NSLog(@"%@", [honzon valueForKey:@"testLogForKeyPath"]);
// —> 不调用方法 崩溃
NSLog(@"%@", [honzon valueForKeyPath:@"testLogForKeyPath"]);
// —> 不调用方法 崩溃

那么,为何会调用testtestLog方法,而传入testLogForKeyPath时,就会崩溃呢?

在valueForKeyPath的文档中有这么一段话:
If so, -valueForKey: is invoked with the first key path component as the argument,and the method being invoked is invoked recursively on the result,

总的来说,可以理解为递归调用 valueForKey:

valueForKey的文档第一条
valueForKey: Searches the class of the receiver for an accessor method whose name matches the pattern -get<Key>, -<key>, or -is<Key>, in that order. If such a method is found it is invoked. If the type of the method's result is an object pointer type the result is simply returned

首先按-get<Key>, -<key>, or -is<Key>的顺序查找getter方法,找到直接调用。如果是bool、int等内建值类型,会做NSNumber的转换。

非常明确的指出,会调用getter方法,所以,在一个方法符合getter命名规则的时,使用valueForKey,是会执行的该方法的,比如NSStringuppercaseString方法

[@"hello" uppercaseString];
// -> @"HELLO"

[@"hello" valueForKey:@"uppercaseString"];
// -> @"HELLO"

[@"hello" valueForKeyPath:@"uppercaseString"];
// -> @"HELLO"

但是,这种做法个人觉得是比较危险,如果出现崩溃,可能会很难定位,所以个人不建议使用如此做法来调用方法

Honzon *honzon = [[Honzon alloc] init];
honzon.name = @"honzon";

NSLog(@"%@",[honzon valueForKeyPath:@"name"]);
// -> @"honzon"

NSLog(@"%@",[honzon valueForKey:@"name"]);
// -> @"honzon"

数组操作

数组去重

//数组去重
NSArray *array1 = @[@"name", @"w", @"aa", @"jimsa", @"aa",@"name"];
NSLog(@"%@", [array1 valueForKeyPath:@"@distinctUnionOfObjects.self"]);//去重
//-> @"name", @"w", @"aa", @"jimsa"]
 
NSLog(@"%@", [array1 valueForKeyPath:@"@unionOfObjects.self"]);//不去重
//-> @[@"name", @"w", @"aa", @"jimsa", @"aa",@"name"]

特定值提取

需要操作对象路径。传入NSString属性的路径,xx.xx形式。

数组中包含对象

 NSArray *array4 = @[
                     @{@"name" : @"cookeee",@"code" : @1},
                     @{@"name": @"jim",@"code" : @2},
                     @{@"name": @"jim",@"code" : @1},
                     @{@"name": @"jbos",@"code" : @1}
                     ];
 
NSLog(@"%@", [array4 valueForKeyPath:@"name"]);      
//-> @[@"cookeee", @"jim", @"jim" , @"jbos"]

NSLog(@"%@", [array4 valueForKeyPath:@"@distinctUnionOfObjects.name"]);//去重
//-> @[@"cookeee", @"jim", @"jbos"]

NSLog(@"%@", [array4 valueForKeyPath:@"@unionOfObjects.name"]);//不去重
//-> @[@"cookeee", @"jim", @"jim" , @"jbos"]

数组之中包含数组

NSArray* pencils = @[@{@"color": @"blue"},
                     @{@"color": @"red"},
                     @{@"color": @"blue"}];
NSArray* markers = @[@{@"color": @"purple"},
                     @{@"color": @"blue"},
                     @{@"color": @"green"}];

NSLog(@"%@",[@[pencils, markers] valueForKeyPath:@"@unionOfArrays.color"]);
// ->  @[@"blue", @"red", @"blue", @"purple", @"blue", @"green"]
NSLog(@"%@",[@[pencils, markers] valueForKeyPath:@"@distinctUnionOfArrays.color"]);
// ->  @[@"green", @"red", @"blue", @"purple"]

实际应用

这是我负责模块的某块代码,因为要存数据库,数据形式为@[@@{},@{},...]

//实际项目中的数据对比
currentTime = CFAbsoluteTimeGetCurrent();
if( adsArray.count != 0 && dbTempArray.count == adsArray.count){
   int count = (int)dbTempArray.count;
   BOOL isSame = YES;
   for (int i = 0 ; i<count && isSame; i++) {
       NSDictionary *dbDict = [dbTempArray objectAtSafeIndex:i];
       for (int j = 0; j<count; j++) {
           NSDictionary *dict = [adsArray objectAtSafeIndex:j];
           if([[dict objectForKey:ADID] isEqualToString:[dbDict objectForKey:ADID]] && [[dict objectForKey:ADSrc] isEqualToString:[dbDict objectForKey:ADSrc]]) {
                [self.adsArray replaceObjectAtSafeIndex:j withObject:dbDict];
                            break;
            }
            if(j == count - 1) {
                isSame = NO;
            }
          }
        //网络获取广告与原加载数据相等 直接return
        if(i == count - 1 && isSame) {
            CFTimeInterval lastTime = CFAbsoluteTimeGetCurrent();
            NSLog(@"%f ms",(lastTime - currentTime)*1000);
            return;
        }
    }
}
CFTimeInterval lastTime = CFAbsoluteTimeGetCurrent();
NSLog(@"%f ms",(lastTime - currentTime)*1000);

// -> 0.008047 ms

而这是我构思的一种替代方案

CFTimeInterval currentTime = CFAbsoluteTimeGetCurrent();

NSSet *adSet = [NSSet setWithArray:[adsArray valueForKeyPath:ADID]];
NSSet *dbSet = [NSSet setWithArray:[dbTempArray valueForKeyPath:ADID]];
NSSet *adStrSet = [NSSet setWithArray:[adsArray valueForKeyPath:ADSrc]];
NSSet *dbStrSet = [NSSet setWithArray:[dbTempArray valueForKeyPath:ADSrc]];
if ([adSet isEqualToSet:dbSet] && [adStrSet isEqualToSet:dbStrSet]) {
     
     CFTimeInterval lastTime = CFAbsoluteTimeGetCurrent();
     NSLog(@"%f ms",(lastTime - currentTime)*1000);
//                return;
}

// -> 0.012994 ms

可以看到,使用valueForKeyPath的效率明显落后于第一种写法,但是代码却缩减了许多。所以,在实际开发中,选择哪种方式,只能根据自身实际情况来斟酌使用

本文大多内容参考如下博客,如有冒犯,请及时指出

未经本人同意,禁止转载

valueForKeyPath

Key-Value Coding: Custom Operators

Objective-C KVC机制

相关文章

  • iOS valueForKeyPath常用用法

    iOS valueForKeyPath常用用法 iOS valueForKeyPath常用用法

  • iOS开发中很实用的技巧

    (一)valueForKeyPath的使用 valueForKeyPath和valueForKey有一些类似,但...

  • 笔记

    数组取值 1.使用 valueForKeyPath valueForKeyPath 取到所有当前key的 valu...

  • valueForKeyPath

    可能大家对- (id)valueForKeyPath:(NSString *)keyPath方法不是很了解。 其实...

  • valueForKeyPath

    1. 数组求和 如果一个数组是由NSNumber或者数字的字符串组成的,可以直接进行进行求和: 2. 数组内字符串...

  • valueForKeyPath

    体验过OC中的: 自然也想用swift玩一把,简单的取值如下:

  • valueForKeyPath

    - (id)valueForKeyPath:(NSString *)keyPath这个方法非常的强大,举个例子: ...

  • valueForKeyPath

    数据操作 确保操作的属性为数字类型,否则运行时刻错误。 对象操作 首先自定义一个测试类Honzon 然后分别将te...

  • 你不知道的valueForKeyPath

    如果说valueForKeyPath只是小小的tips,那真的可以说valueForKeyPath是偏方治大病。 ...

  • iOS之valueForKeyPath

    使用valueForKeyPath 大家好,我是亮亮。今天要说的是valueForKeyPath方法,而不是数组取...

网友评论

      本文标题:valueForKeyPath

      本文链接:https://www.haomeiwen.com/subject/hbdyottx.html