美文网首页
重写模型类Description的简便写法

重写模型类Description的简便写法

作者: ShenYj | 来源:发表于2016-08-25 16:00 被阅读39次

字典转模型,在模型类中往往需要重写description方法,便于我们查看模型的各个属性信息

一般的写法是:

- (NSString *)description{
    
    return [NSString stringWithFormat:@"name:%@,age:%@",self.name,self.age];
}

这种方式需要拼接,如果属性过多,使用麻烦
这里介绍一个KVC的另外一个方法(模型转字典)

  • OC写法
- (NSString *)description{
    
    NSArray *keys = @[@"name",@"age"];
    
    return [self dictionaryWithValuesForKeys:keys].description;
    
}
  • Swift写法
    override var description: String {
        let keys = ["name","age"]
        return dictionaryWithValuesForKeys(keys).description
    }

相关文章

网友评论

      本文标题:重写模型类Description的简便写法

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