欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

iOS底层原理——KVC使用实践以及实现,

来源: 开发者 投稿于  被查看 39383 次 评论:288

iOS底层原理——KVC使用实践以及实现,


简介

KVC(Key-value coding)键值编码,顾名思义。额,简单来说,是可以通过对象属性名称(Key)直接给属性值(value)编码(coding)“编码”可以理解为“赋值”。这样可以免去我们调用getter和setter方法,从而简化我们的代码,也可以用来修改系统控件内部属性(这个黑魔法且用且珍惜)。

1. 最简单的使用例子

  • 假设有CYXModel类与CYXShopModel类,CYXModel里面有nameproduct属性,CYXShopModel里面有productName属性。
@interface CYXModel: NSObject 
@property (nonatomic, strong) NSString *name; 
@property (nonatomic, strong) CYXShopModel *product; 
@end 

@interface CYXShopModel: NSObject 
@property (nonatomic, strong) NSString * productName; 
@end 

  • 不使用KVC,我们这样访问CYXModel的属性
    • 取值:
CYXModel *model = [[CYXModel alloc]init];
NSString *name = model. name;
CYXShopModel *shop = model. product;
NSString *productName = shop. productName;

  • 设值:
CYXModel *model = [[CYXModel alloc]init];
model. name = @"CYX";
CYXShopModel *shopModel = [[CYXShopModel alloc]init];
shopModel. productName = @"NIKE";
model. product = shopModel;

  • 使用KVC,我们可以这样访问CYXModel的属性
  • 取值:
CYXModel *model = [[CYXModel alloc]init];
NSString  *name = [model valueForKey: @"name" ];
NSString  *productName = [model valueForKeyPath: @"product.productName" ];

  • 设值:
CYXModel *model = [[CYXModel alloc]init];
[model setValue:@"CYX" forKey:@"name"];
[model setValue:@"NIKE" forKeyPath:@"product.productName"];


注: 这个简单的例子,可能你看了觉得这并没什么卵用,下面我们来分析一下稍微有点卵用的例子吧。

2. KVC字典转模型的实现原理

  • 假设dict字典中有name,icon的Key,CYXModel模型类中必须要有同名的name,icon属性与之相对应。

  • 我们使用[CYXModel setValuesForKeysWithDictionary:dict];进行字典转模型。

  • setValuesForKeysWithDictionary:方法内部实现原理如下:

    • (1) 遍历字典里面所有的key和值,name,icon。
        // enumerateKeysAndObjectsUsingBlock:遍历字典中的所有keys和valus
    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 利用KVC给模型中属性赋值,,
        // key:用来给哪个属性
        // Value:给模型的值
        [CYXModel setValue:obj forKey:key];
    }];
    
    
    • (2) 分别给属性赋值
      • [CYXModel setValue:dict[@"name"] forKey:@"name"];
      • [CYXModel setValue:dict[@"icon"] forKey:@"icon"];
  • setValue:forKey:方法:给模型的属性赋值

    • 赋值原理:
      • (1)去模型中查找有没有setIcon方法,就直接调用这个set方法,给模型这个属性赋值[self setIcon:dict[@"icon"]];
      • (2)如果找不到set方法,接着就会去寻找有没有icon属性,如果有,就直接访问模型中icon = dict[@"icon"];
      • (3)如果找不到icon属性,接着又会去寻找_icon属性,如果有,直接_icon = dict[@"icon"];
      • (4)如果都找不到就会报错
        [<Flag 0x7fb74bc7a2c0> setValue:forUndefinedKey:]
  • 扩展:读者可以去查查KVV(键值验证),进一步理解报错原因与容错方法。

作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:519832104 不管你是小白还是大牛欢迎入驻,分享经验,讨论技术,大家一起交流学习成长!

另附上一份各好友收集的大厂面试题,需要iOS开发学习资料、面试真题,可以添加iOS开发进阶交流群,进群可自行下载!

3. 修改系统控件内部属性(runtime + KVC)

  • 有时候,UI会闲着没事,会给你找点事情,例如,界面设计图是这样的:

  • 这。。怎么感觉有点不同,这UIPageControl怎么跟我平常用的不一样?平常不都是这样的??如下图

  • 首先想到的肯定是,查看UIPageControl的头文件,如下:

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIPageControl : UIControl 

@property(nonatomic) NSInteger numberOfPages;          // default is 0
@property(nonatomic) NSInteger currentPage;            // default is 0\. value pinned to 0..numberOfPages-1

@property(nonatomic) BOOL hidesForSinglePage;          // hide the the indicator if there is only one page. default is NO

@property(nonatomic) BOOL defersCurrentPageDisplay;    // if set, clicking to a new page won't update the currently displayed page until -updateCurrentPageDisplay is called. default is NO
- (void)updateCurrentPageDisplay;                      // update page display to match the currentPage. ignored if defersCurrentPageDisplay is NO. setting the page value directly will update immediately

- (CGSize)sizeForNumberOfPages:(NSInteger)pageCount;   // returns minimum size required to display dots for given page count. can be used to size control if page count could change

@property(nullable, nonatomic,strong) UIColor *pageIndicatorTintColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
@property(nullable, nonatomic,strong) UIColor *currentPageIndicatorTintColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;

@end

  • 卧槽,就这么几个属性可以给我设的,不够用啊兄弟。能不能给我个可以赋值UIImage对象的属性?看来正常途径使用系统的控件是设不了了,剩下的我感觉只有两种方法(如有其它,欢迎指出),一种是自定义PageControl,这种方式看起来不简单,各位有兴趣可以去试试。另一种方式就是,通过runtime遍历出UIPageControl所有属性(包括私有成员属性,runtime确实很强大)。
  • 使用runtime遍历UIPageControl结果(下篇文字再谈谈runtime,这里暂不解释)如下打印:
2016-03-23 01:09:26.161 TenMinDemo[6224:507269] UIPageControl -> _lastUserInterfaceIdiom = q
2016-03-23 01:09:26.161 TenMinDemo[6224:507269] UIPageControl -> _indicators = @"NSMutableArray"
2016-03-23 01:09:26.161 TenMinDemo[6224:507269] UIPageControl -> _currentPage = q
2016-03-23 01:09:26.161 TenMinDemo[6224:507269] UIPageControl -> _displayedPage = q
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _pageControlFlags = {?="hideForSinglePage"b1"defersCurrentPageDisplay"b1}
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _currentPageImage = @"UIImage" // 当前选中图片
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _pageImage = @"UIImage" // 默认图片
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _currentPageImages = @"NSMutableArray"
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _pageImages = @"NSMutableArray"
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _backgroundVisualEffectView = @"UIVisualEffectView"
2016-03-23 01:09:26.162 TenMinDemo[6224:507269] UIPageControl -> _currentPageIndicatorTintColor = @"UIColor"
2016-03-23 01:09:26.163 TenMinDemo[6224:507269] UIPageControl -> _pageIndicatorTintColor = @"UIColor"
2016-03-23 01:09:26.163 TenMinDemo[6224:507269] UIPageControl -> _legibilitySettings = @"_UILegibilitySettings"
2016-03-23 01:09:26.163 TenMinDemo[6224:507269] UIPageControl -> _numberOfPages = q

  • 结果非常满意,果然找到我想要的图片设置属性。
  • 然后通过KVC设置自定义图片,实现了效果,代码如下:
 UIPageControl *pageControl = [[UIPageControl alloc] init]; 
 [pageControl setValue:[UIImage imageNamed:@"home_slipt_nor"] forKeyPath:@"_pageImage"];
 [pageControl setValue:[UIImage imageNamed:@"home_slipt_pre"] forKeyPath:@"_currentPageImage"];

  • 注:
    这里只是抛砖引玉的讲了个小例子,其他的神奇功能等待读者去发现啦。

提示: 在xib/Storyboard中,也可以使用KVC,下面是在xib中使用KVC把图片边框设置成圆角


点击此处,立即与iOS大牛交流学习

相关文章

    暂无相关文章

用户评论