使用category为delegate和protocol解耦

2017-11-22  本文已影响154人  骑着老鼠虐大象

项目中我们有时候会遇到一些情况,需要经常使用某个代理,但是又不是都需要遵从协议,这时候就可以用我的这种方式完全解耦,一些小东西,欢迎指点和指指点点。下面直接开始:

要是大家闲看的麻烦,可以直接下载:https://github.com/IDwangluting/DeleagateOperation.git

demo 中 总共用了几个文件 ,
Viewcontroller,
newDeleagte.h,
UIViewController+Protocol,
UIViewController+Delegate

然后viewcontroller 中的代码是这样的:

import "ViewController.h"

import "UIViewController+Delegate.h"
import UIViewController+Protocol.h"

@implementation ViewController

-(void)viewDidLoad {
[super viewDidLoad];
self.delegate = self ;
[self addProtocol];
}

-(void)dealloc {
[self removeDelegate];
}

NewDeleagte.h 中的代码在下面,这里只有 协议的申明,

import <Foundation/Foundation.h>

@protocol NewDelegate <NSObject>

-(void)viewWillEnter;

-(void)viewDidEnter;

-(void)viewWillOut;

-(void)viewDidOut;

@end

UIViewController+Protocol.h 中的代码是这样的:

import "NewDelegate.h"

@interface UIViewController (Protocol)

@property (nonatomic,assign)id<NewDelegate> delegate ;

-(void)addProtocol ;

-(void)removeDelegate;

@end

UIViewController+Protocol.m 中的代码在下面,这里遵从了协议

import "UIViewController+Protocol.h"
import <objc/runtime.h>

@implementation UIViewController (Protocol)

-(void)setDelegate:(id<NewDelegate>)delegate {
objc_setAssociatedObject(self, @selector(delegate), delegate, OBJC_ASSOCIATION_ASSIGN);
}

-(id<NewDelegate>)delegate {
return objc_getAssociatedObject(self, @selector(delegate)); ;
}

-(void)addProtocol {

if (self.delegate  && [self.delegate respondsToSelector:@selector(viewWillEnter)]) {
  [self.delegate viewWillEnter];
}

if (self.delegate  && [self.delegate respondsToSelector:@selector(viewDidEnter)]) {
    [self.delegate viewDidEnter];
}

if (self.delegate  && [self.delegate respondsToSelector:@selector(viewWillOut)]) {
    [self.delegate viewWillOut];
}

if (self.delegate  && [self.delegate respondsToSelector:@selector(viewDidOut)]) {
    [self.delegate viewDidOut];
}

}

-(void)removeDelegate {
self.delegate = nil ;
}

UIViewController+Delegate.h 中的代码在下面,这里实现了代理

import "NewDelegate.h"

@interface UIViewController (Delegate) <NewDelegate>

@end

UIViewController+Delegate.m 中的代码是这样的:

import "UIViewController+Delegate.h"

@implementation UIViewController (Delegate)

-(void)viewWillEnter {
NSLog(@" line:%d method:%s",LINE,FUNCTION);
}

-(void)viewDidEnter {
NSLog(@" line:%d method:%s",LINE,FUNCTION);
}

-(void)viewWillOut {
NSLog(@" line:%d method:%s",LINE,FUNCTION);
}

-(void)viewDidOut {
NSLog(@" line:%d method:%s",LINE,FUNCTION);
}

其实这是前几天面试的时候,帮别人解决问题时想的一个方案,他当然大喜过望了。希望对大家有用吧!

上一篇 下一篇

猜你喜欢

热点阅读