• Objective C 总结(十一):KVC


    KVC提供了以字符串的方式访问对象的数据,由于要解析字符串,所以性能有损耗

    - (id) valueForKey: (NSString *) key;
    - (void) setValue: (id) value forKey: (NSString *) key;
    
    - (id) valueForKeyPath: (NSString *) keyPath;
    - (void) SetValue: (id) value forKeyPath: (NSString *) keyPath;

    Objective-C在运行时使用元数据进入对象查找相关的信息,valueForKey:首先,查找以-key或isKey命名的getter方法,如果不存在getter方法,则会去查找_key或key命名的字段。

    KVC提供了自动装箱的功能,以对值类型进行操作

    // 199进行了装箱NSNumber
    [somePerson setValue: 199 forKey: @"height"]
    // 拆箱
    [somePerson valueForKey: @"height"]

    获取集合

    // 获取两只手的宽度集合
    NSArray *array = [somePerson valueForKeyPath: @"hands.width"]
    // array ( 15, 15.5)

    进行运算

    @count, @sum, @avg, @min, @max, @distinctUnionOfObjects

    // 获取hand个数
    [somePerson valueForKeyPath: @"hands.@count"]
    
    [somePerson valueForKeyPath: @"hands.@sum.width"]
    
    [somePerson valueForKeyPath: @"hands.@avg.width"]
    
    [somePerson valueForKeyPath: @"hands.@min.width"]
    
    [somePerson valueForKeyPath: @"hands.@max.width"]
    // 剔除穿着的同一品牌服饰
    [somePerson valueForKeyPath: @"wears.@distinctUnionOfObjects.brand"]

    批处理

    - (id) dictionaryWithValuesForKeys: (NSArray *) array;
    - (void) setValuesForKeysWithDictionary: (NSDictionary *) dictionary;
    
    NSArray *keys = @[@"bob", @"smith"];
    NSDictionary *dictionary = [somePerson dictionaryWithValuesForKeys: keys];
    
    [somePerson setValuesForKeysWithDictionary: dictionary];
  • 相关阅读:
    众包兼职平台有哪些?
    提高页面速度的10种相对简单方法
    如何设计第三方账号登陆
    Nginx的配置参数中文说明
    确定你已经彻底搞懂Nginx了
    云编程,这是我见过最优雅的Web云端集成开发IDE-Cloud Studio
    Excel制作三级下拉菜单
    Excel多人共享
    spring_2_注入详解
    spring_1_工厂与第一个 Spring 程序
  • 原文地址:https://www.cnblogs.com/iprogrammer/p/3247422.html
Copyright © 2020-2023  润新知