valueForKeyPath

数据操作

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

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机制

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容