教你如何使用KVC

KVC 就是 key value coding,废话!

  • 今天我们研究的是如何使用它!

    key value coding : 间接通过字符串类型的key取出对应的属性值

KVC的价值

  • 1.可以访问私有成员变量的值
  • 2.可以间接修改私有成员变量的值(替换系统自带的导航栏、tabbar)
    举个例子:我现在要替换系统自带的tabbar,但是,系统的是“ readonly”的。解决方法是:KVC。
    // 替换系统的tabbar
    [self setValue:[[MyTabBar alloc] init] forKeyPath:@"tabBar"];
  • 我们点击@"tabBar" 进去之后会发现:是readonly 属性的。
    @property(nonatomic,readonly) UITabBar *tabBar NS_AVAILABLE_IOS(3_0);
    // Provided for -[UIActionSheet showFromTabBar:]. Attempting to modify the contents of the tab bar directly will throw an exception.

进一步了解

keyPath包含了key的功能
key:只能访问当前对象的属性
keyPath:能利用.运算符一层一层往内部访问属性

  • 到底有啥好用???
KVC 可是Cocoa的一大招!为啥我这么说呢?
  • 下面请看一个例子:
    @interface DataModel : NSObject
    @property (nonatomic,strong)NSString *applicationId;
    @property (nonatomic,strong)NSString *slug;
    @property (nonatomic,strong)NSString *name;
    @property (nonatomic,strong)NSString *releaseDate;
    @property (nonatomic,strong)NSString *version;
    @property (nonatomic,strong)NSString *descriptionStr;//现在和json,key不一致
    @property (nonatomic,assign)int categoryId;
    @property (nonatomic,strong)NSString *categoryName;
    @property (nonatomic,strong)NSString *iconUrl;
    @property (nonatomic,strong)NSString *itunesUrl;
    @property (nonatomic,strong)NSString *starCurrent;
    @property (nonatomic,strong)NSString *starOverall;
    @property (nonatomic,strong)NSString *ratingOverall;
    @property (nonatomic,strong)NSString *downloads;
    @property (nonatomic,strong)NSString *currentPrice;
    @property (nonatomic,strong)NSString *lastPrice;
    @property (nonatomic,strong)NSString *priceTrend;
    @property (nonatomic,strong)NSString *expireDatetime;
    @property (nonatomic,strong)NSString *releaseNotes;
    @property (nonatomic,strong)NSString *updateDate;
    @property (nonatomic,strong)NSString *fileSize;
    @property (nonatomic,strong)NSString *ipa;
    @property (nonatomic,strong)NSString *shares;
    @property (nonatomic,strong)NSString *favorites;

    @end
    
  • 以上的model 不少了吧!我们开发时不可能像下面那样,一个一个地写吧!太Low了:
    DataModel *model = [[DataModel alloc] init];
    cell.xxx.text = model.name;
    cell.xxx.text = model.descriptionStr;
    xxx.xxx.xxx = model. applicationId;
    ...
    ...

那么怎么样才能一次性解决掉这个问题呢?---用KVC

  • 使用KVC 的步骤非常简单,要记住!就是重写2个方法而已!

  • 重写2个方法:
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{ }

    -(id)valueForUndefinedKey:(NSString *)key{
      return nil;
    }
    

下面是常见使用:

  • KVC的前提是保证 模型里的属性要和JSON 解析的值一致!

  • 上面的模型属性里有一个和json解析不一样的字段,descriptionStr;//现在和json,key不一致 ,json解析的是description。

  • 不一致的原因是模型的属性尽量不要和系统的关键字一致!所以,我们模型要避开关键字。那么问题来了,我们怎么设置值一致呢?

  • 很简单!!!只需在重写的方法里替换就OK啦!
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{

     //找到和属性不一致名字的key,然后赋值给self的属性
      if ([key isEqualToString:@"description"]) {
      
    // self.descriptionStr = value; // 不推荐使用
        [self setValue:value forKey:@"descriptionStr"]; // 推荐
      }
    }
    
  • 例如:id、description等等系统关键字就可以用这种方法做了。

上面是解决关键字,也就是属性名字和系统关键字有冲突!!!,下面介绍的,也是开发中经常遇到的问题:就是对于处理“类型”,就用下面的方法:
  • 类型?

  • 这就是类型:服务器返回有“引号”和没引号,分别代表 NSString 和NSNumber


    看有没有引号.png
  • 这个对KVC 也有影响,下面我带大家 处理类型!!!

  • 事实上,在企业服务器开发人员把 NSString修改成 NSNumber 类型或其它类型,他们通常是不会主动告诉你的!这是你之前可以成功运行的APP突然崩溃!这你又得花费很多时间去查找!为了避免此问题和如何处理,请看下面:

  • 重写方法:
    - (void)setValue:(id)value forKey:(NSString *)key{}

  • 这里就以 NSNumber 为例子:
    - (void)setValue:(id)value forKey:(NSString *)key
    {
    // 服务器是 NSNumber ,模型表里是 NSString类型,所以,要处理
    if ([value isKindOfClass:[NSNumber class]]) {

       // NSNumber--> NSString
       [self setValue:[NSString stringWithFormat:@"%@",value] forKey:key];
      
    }else{
        [super setValue:value forKey:key];
       }
    }
    

总结:使用KVC时,最好重写2个方法 和 一个处理 类型的方法;

  • 下面再次回顾上面的方法使用:
    #pragma mark ---- 一定要实现下面的两个方法!(属性名字用这个方法)
    /**
    利用kvc解析json,一定要实现下面的两个方法!(属性名字用这个方法)
    */
    -(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //找到和属性不一致名字的key,然后赋值给self的属性
    if ([key isEqualToString:@"description"]) {

    // self.descriptionStr = value; // 不推荐使用
      [self setValue:value forKey:@"descriptionStr"]; // 推荐
      }
    }
    
    
    -(id)valueForUndefinedKey:(NSString *)key{
        return nil;
    }
    
    #pragma mark --- 对于处理“类型”,就用下面的方法
    
    // 处理特殊 ----(类型)例如:NSNumber--> NSString
    - (void)setValue:(id)value forKey:(NSString *)key
    

    {
    // price 服务器是 NSNumber
    // 服务器是 NSNumber ,模型表里是 NSString类型,所以,要处理
    if ([value isKindOfClass:[NSNumber class]]) {

      // NSNumber--> NSString
      [self setValue:[NSString stringWithFormat:@"%@",value] forKey:key];
    

    }else{
    [super setValue:value forKey:key];
    }
    }

  • 其实KVC的使用场景还有,这里就不介绍了!这个是在开发中非常常用的!!!

  • 你感受到了KVC好处了吗?

下一篇是KVC 和 CoreData技术相结合(欢迎关注!!!)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • KVC(Key-value coding)键值编码,单看这个名字可能不太好理解。其实翻译一下就很简单了,就是指iO...
    朽木自雕也阅读 1,591评论 6 1
  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,788评论 0 9
  • 【2017年最新】☞ iOS面试题及答案 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经...
    紫色冰雨阅读 624评论 0 1
  • 设计模式是什么? 你知道哪些设计模式,并简要叙述? 设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型的...
    琦均煞Sylar阅读 428评论 0 0
  • 文艺片就一定要文艺到极致才行。 本君新近看了一部老电影,是韩国导演金基德的《空房间》。这部电影又译为《空房诱奸》,...
    奥妙全自动阅读 850评论 0 6