Code Monkey home page Code Monkey logo

yskvo's Introduction

YSKVO

自定义KVO实现

环境

Objective-C iOS11

与苹果提供的KVO相比:

优势

1、移除KVO不再是必须步骤,不移除也可以,因为提供的功能包含了自动移除的功能

2、在监听回调的block里面,可以设置回调是否在主线程执行

3、一个监听一个回调,简单清晰,相比系统自带的所有回调都在observerValueForKeypath中执行,更加清晰

4、放心使用,此提供的功能是线程安全的

劣势

1、只提供监听key,未提供keypath

使用

1、pod 'YSKVO'

2、pod install

3、import <YSKVO/YSKVO.h>

添加观察者

// 对per的name属性进行观察
[self.per ys_addObserver:self forKey:@"name" withCallbackOnMainthread:false andCallback:^(id  _Nonnull observedObject, NSString * _Nonnull observedKey, id  _Nonnull oldValue, id  _Nonnull newValue) {
    NSLog(@"%@, %@, %@, %@, %@", [NSThread currentThread], observedObject, observedKey, oldValue, newValue);
}];

移除观察者

// 移除方法非必须,因为在调用kvo的block前,会自动把observer为nil的移除
// 提供移除方法,主要是为了在某些场景下,需要手动进行移除

// 结合key和观察者移除
[self.per ys_removeObserver:self forKey:@"name"];

// 移除观察者的所有观察
[self.per ys_removeObserver:self];

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.