zoukankan      html  css  js  c++  java
  • 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];
  • 相关阅读:
    『题解』POJ1753 Flip Game
    『数论』乘法逆元
    『数据结构』RMQ问题
    UVA 253 Cube painting 【数学】
    POJ 1852 Ants 【水+Trick+贪心】
    POJ 2955 Brackets 【区间DP】
    LOJ 1422 Halloween Costumes【区间DP】
    HDU 4193 Non-negative Partial Sums 【单调队列】
    CodeForces-545C Woodcutters 【贪心+机智】
    CodeForces 19D A and B and Interesting Substrings 【前缀和】
  • 原文地址:https://www.cnblogs.com/iprogrammer/p/3247422.html
Copyright © 2011-2022 走看看