iOS面试题之 KVO KVC MVC

2016-07-22  本文已影响0人  橙色酱油cc

KVC 与 KVO
1,KVC:NSKeyValueCoding 键值编码:是一种用字符串间接访问对象属性的机制.
key就是确定对象某个值的字符串,即属性的名称,通常与系统访问器方法同名,并且以小写字母开头.
获取属性值可以通过 valueForKey 方法,设置属性值可以通过 setValue:forKey 方法.同时, KVC 还对未定义的属性值定义了 valueForUndefinedKey: 方法,可以重载以获取想要的实现.
举个🌰:字典转模型(swift 版本)
创建 Person 类

class Person: NSObject {
    var name:String?
    //字典转模型时其中的基本数据类型不可为可选类型,否则在 KVC 赋值中会找不到对应的 key 值从而发生 crash. 如果为可选类型的话,应该给初始值
    var age:Int = 0
    var gender:String?

    //字典转模型
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }

取值:

        let person = Person(dict: dict)
        print(person.name)
        print(person.age)
        print(person.gender)

2,KVO:NSKeyValueObserving 键值监听:定义了这种机制,当对象的属性值发生变化时,我们能收到通知.
同样举个🌰:
创建 view

@property (nonatomic, strong) UIView *myView;

设置 view

    self.myView = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
    self.myView.backgroundColor = [UIColor cyanColor];
//创建 button, 点击方法是改变myView 的背景颜色
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [btn setTitle:@"变色" forState:(UIControlStateNormal)];
    btn.frame = CGRectMake(150, 400, 100, 100);
    btn.backgroundColor = [UIColor redColor];
    [btn addTarget:self action:@selector(btnAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:btn];
    [self.view addSubview:self.myView];

实现点击方法

- (void)btnAction
{
    //添加观察者
    //第二个参数:被观察者的属性
    [self.myView addObserver:self forKeyPath:@"backgroundColor" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    self.myView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.f];
}

观察者方法

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    self.view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.f];
    //移除观察者模式(也可以重写 dealloc 来移除观察者)
    [self.myView removeObserver:self forKeyPath:@"backgroundColor"];
}

如此便可以实现,当点击 button 改变 myView 的背景颜色时, self.view 的背景颜色也随之改变.

MVC:Model-View-Controller:是 iOS 开发中的一种设计模式, model 主要负责管理模型数据,view 是 UI 的重要控件,view 上的显示内容有 model 决定,如何显示有 controller 决定. controller是管理 UI 的重要组件,管理视图的显示隐藏等属性,实现代理方法,监听交互事件等.

.

上一篇下一篇

猜你喜欢

热点阅读