Notification和KVO

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)
    }
}

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

推荐阅读更多精彩内容

  • Delegate 优点: 语法严格, 所有将要听到的事件必须在delegate 协议中有清晰的定义 delegat...
    凌晨四点的洛杉矶阅读 383评论 0 2
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,276评论 4 61
  • 1、工作 以前对工作上的问题处理觉得没必要,得过且过。所有碰到的问题能够解决到60分就可以了。但是,这个60分一方...
    王晓杰_2c01阅读 157评论 0 0
  • 追完剧,刷刷微博,看看各种撕X,毫无睡意。要是搁以前定会焦躁到抓狂,明早还得早起,办公室还有活儿,然后噼里啪啦的各...
    甜甜圈爱柠檬Bingo阅读 160评论 0 1
  • 听十点读书的时候听到毕淑敏《生命借记卡》,觉得这个字很妙,生活中有多少是自己借的,然后一点点的偿还。金钱,爱...
    暮晓玲珑阅读 229评论 0 0