Notification和KVO

作者: 光明程辉 | 来源:发表于2016-10-31 00:30 被阅读36次

Notification

//1:注册监听
//订阅NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"test" object:nil];

//2:监听事件
- (void)receiveNotification:(id)sender {
    NSLog(@"receive msg is:%@",sender);
}

//3:发送notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self.testString];

KVO

objc


//1:设置监听对象
//@property(nonatomic,strong) NSString *testString;
[self addObserver:self forKeyPath:@"testString" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"testString has changed"];

//2:注册监听
//当发起监听的对象的对应keypath改变时,即引起事件 !!!!!注意:使用_testString的方法不起作用!!!!!!!
self.testString = @"hello observe !!!";

//3:注册监听委托方法
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"%@",context);
}

swift


//监听是否可以前进后退,修改btn.enable属性
webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
//监听加载进度
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)

//重写self的kvo方法
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if (keyPath == "loading") {
        gobackBtn.enabled = webView.canGoBack
        forwardBtn.enabled = webView.canGoForward
    }
    if (keyPath == "estimatedProgress") {
        //progress是UIProgressView
        progress.hidden = webView.estimatedProgress==1
        progress.setProgress(Float(webView.estimatedProgress), animated: true)
    }
}

相关文章

  • Notification和KVO

    Notification KVO objc swift

  • iOS面试题-每日十道-第七天

    一. Notification和KVO有什么不同?KVO在ObjC中是怎么实现的? KVO:只能监听属性值的变化...

  • 问题

    1. Notification和KVO有什么不同?KVO在ObjC中是怎么实现的? KVO:只能监听属性值的变化,...

  • 心动

    KVO,delegate和notification是A和B双方合作的事情,而KVO是B单方面的事情。 A有消息了,...

  • KVO的原理实现

    一、什么是KVO KVO和Notification是Objective-C语言中观察者模式的两种实现机制。KVO指...

  • Delegate、Notification 和 KVO

    Delegate 优点: 语法严格, 所有将要听到的事件必须在delegate 协议中有清晰的定义 delegat...

  • ReactiveCocoa(RAC)初探

    Notification通知 ControlEvent事件 GestureRecognizer手势作 KVO De...

  • 面试目录

    一面: 设计模式 Notification、Delegate KVO、KVC block NSThread、GCD...

  • 2018年iOS经典面试题

    1、什么时候用delegate,什么时候用Notification? 2、什么是 KVO 和 KVC? 3、KVC...

  • KVC KVO Notification

    一、KVC(key value code)的基本概念和用法 1、基本概念 2、适用情况:将服务器的内容转化为数据模...

网友评论

    本文标题:Notification和KVO

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