函数式编程自定义KVO

写在前面:今天周末,没有出门,就结合这两天学的,敲了这个demo, 水平有限,表要喷,当然很多都是站在大牛的肩膀上,没有大牛的肩膀,我早就饿死了.....对于比较懒惰的我来说,今天过的很充实啊,听着民谣、玩着代码、隔壁还坐着一个看电视的媳妇儿,哈哈。
在iOS开发中,苹果给我们提供了很多回机制,KVO(key-value-observing)就是其一。在某个对象注册监听者后,在被监听的对象发生改变时,对象会发送一个通知给监听者,以便监听者执行回调操作。今天这篇文章主要是为了实现结合函数式编程思想,自定义KVO的。其主要步骤是动态生成子类和实现消息转发,具体如代码:

步骤

  1. KVO 实例
  2. 动态生成子类
  3. setter方法
  4. 消息转发

先来创建两个类,分别是People类和KVOInfoModel类
People类

People.h
 # import 
 @interface People : NSObject
 @property (nonatomic,strong) NSString *name;
 @property (nonatomic,strong) NSString *age;
 @end
KVOInfoModel.h
 #import 
 typedef void(^KVOBlock) (id observer,NSString *keyPath,id newValue,id oldValue);
 @interface KVOInfoModel : NSObject
 @property (nonatomic, copy) NSString *keyPath;
 @property (nonatomic, weak) NSObject *observer;
 @property (nonatomic, copy) KVOBlock blockHandle;
 - (instancetype)initWithObserver:(NSObject *)observer keyPath:(NSString *)keyPath observerHandle:(KVOBlock)blockHandle;
 @end
KVOInfoModel.m
 #import "KVOInfoModel.h"
 @implementation KVOInfoModel
 - (instancetype)initWithObserver:(NSObject *)observer keyPath:(NSString *)keyPath observerHandle:(KVOBlock)blockHandle{
     if (self = [super init]) {    
         _keyPath = keyPath;
         _observer = observer;
         _blockHandle = blockHandle;        
     } 
     return self;
 }
 @end
再来一个NSObject (KVO) .h
 #import 
 #import "KVOInfoModel.h"
 @interface NSObject (KVO)
 - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath withBlock:(KVOBlock)block;
 @end
NSObject (KVO) .m
  #import "NSObject+KVO.h"
  #import 
 #import "KVOInfoModel.h"
  @implementation NSObject (KVO)
  - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath withBlock:(KVOBlock)block{

//1. 实例 SEL 方法选择器
SEL setterSeletor = NSSelectorFromString(setterfromGetter(keyPath));
Method setterMethod = class_getInstanceMethod(object_getClass(self), setterSeletor);
if (!setterMethod) {
    @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"没有setter方法" userInfo:nil];
}

//2. 动态创建子类
NSString *superClassName = NSStringFromClass([self class]);

Class newClas = [self creatClassFromSuperClass:superClassName];

//ias swilzing 替换父类
object_setClass(self, newClas);

const char *types = method_getTypeEncoding(setterMethod);

//3:setter方法
class_addMethod(newClas, setterSeletor, (IMP)KVO_Setter, types);

//4;消息转发
KVOInfoModel *info = [[KVOInfoModel alloc] initWithObserver:observer keyPath:keyPath observerHandle:block];

NSMutableArray *obserArray = objc_getAssociatedObject(self, (__bridge const void * _Nonnull)(KVOAssioKey));

if (!obserArray) {
    
    obserArray = [NSMutableArray arrayWithCapacity:1];
    
    /**
     关联属性
     1:对象
     2:关键字
     3:关联对象
     4:策略
     */
    objc_setAssociatedObject(self, (__bridge const void * _Nonnull)(KVOAssioKey), obserArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}  
[obserArray addObject:info];   }

pragma mark - 函数区域

 /* 将name转变成setName: */
 static NSString * setterfromGetter(NSString * getter){
     if (getter.length <= 0) {return  nil;}  
     // name
     NSString *firstString = [[getter substringToIndex:1] uppercaseString]; // N
     NSString *leaveSTring = [getter substringFromIndex:1]; // ame   
     return [NSString stringWithFormat:@"set%@%@:",firstString,leaveSTring];
 }
 /* 将setName转变成name */
 static NSString *getterfromSetter(NSString * setter){  
     if (setter.length <= 0 || ![setter hasPrefix:@"set"] || ![setter hasSuffix:@":"]) { return nil;}  
     //setName:  ===>> Name:  ====> Name ==> name  
     NSRange range = NSMakeRange(3, setter.length-4);
     NSString *getter = [setter substringWithRange:range];
     NSString *firstString = [[getter substringToIndex:1] lowercaseString]; //n
     getter = [getter stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:firstString]; 
     return getter;
 }
 /* 动态生成子类*/
 static Class KVC_Class(id self){
     return class_getSuperclass(object_getClass(self));
 }
 - (Class)creatClassFromSuperClass:(NSString *)superName{   
     Class superClass = NSClassFromString(superName);
   /**
 动态生成类
 1:父类
 2:名字
 3:空间
 */
// NSKVONotifiying_   ===>>> KCKVC_
NSString *newClassName = [KVOPre stringByAppendingString:superName];
Class newClass = NSClassFromString(newClassName);
if (newClass) {
    return newClass;
}

newClass = objc_allocateClassPair(superClass, newClassName.UTF8String, 0);

//添加Class
Method classMethod = class_getClassMethod(superClass, @selector(class));

const char *type = method_getTypeEncoding(classMethod);
/**
 添加方法
 1:类
 2:方法名字
 3:IMP  函数实现的指针
 4:类型
 */
class_addMethod(newClass, @selector(class), (IMP)KVC_Class, type);
//注册类
objc_registerClassPair(newClass);   
return newClass;
}
  static void KVO_Setter(id self,SEL _cmd,id newValue){

//手动监听
//_cmd ===


NSString *setterName = NSStringFromSelector(_cmd);
NSString *getterName = getterfromSetter(setterName);

id oldValue = [self valueForKey:getterName];

[self willChangeValueForKey:getterName];

//消息转发

void(*KCMsgSend)(void *,SEL,id) = (void *)objc_msgSendSuper;

struct objc_super kcSuperStruct = {
    .receiver = self,
    .super_class = class_getSuperclass(object_getClass(self))
};

KCMsgSend(&kcSuperStruct,_cmd,newValue);


[self didChangeValueForKey:getterName];



NSMutableArray *obserArray = objc_getAssociatedObject(self, (__bridge const void * _Nonnull)(KVOAssioKey));

for (KVOInfoModel *info in obserArray) {
    dispatch_async(dispatch_queue_create(0, 0), ^{
        info.blockHandle(self, info.keyPath, newValue, oldValue);
    });
}



  }

  @end
VC回调KVO
  #import "ViewController.h"
  #import "People.h"
  #import "NSObject+KVO.h"
  @interface ViewController ()

  @property (nonatomic,strong) People *people;

  @end

  @implementation ViewController

  - (void)viewDidLoad {
      [super viewDidLoad];

      self.people = [[People alloc] init];

      [self.people addObserver:self forKeyPath:@"name" withBlock:^(id observer, NSString *keyPath, id newValue, id oldValue) {
          NSLog(@"%@==%@",newValue,oldValue);

      }];
      [self.people addObserver:self forKeyPath:@"age" withBlock:^(id observer, NSString *keyPath, id newValue, id oldValue) {
          NSLog(@"%@==%@",newValue,oldValue);
    
      }];
      self.people.name = @"hanhan";
      self.people.age = @"100";
  }
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

      self.people.name = [NSString stringWithFormat:@"%@+",self.people.name];
      self.people.age = [NSString stringWithFormat:@"%@+",self.people.age];
  }

  - (void)dealloc{
      [self.people removeObserver:self forKeyPath:@"name"];
  }

这样就是实现了一个自定义KVO,面试时用起来绝对6的一比,还没有具体使用到项目中,今后会继续学习,不断提升自己。
END

你可能感兴趣的:(函数式编程自定义KVO)