美文网首页
Swift 中实现 Proxy,封装UITableView

Swift 中实现 Proxy,封装UITableView

作者: 万物皆有破绽 | 来源:发表于2017-03-31 15:48 被阅读0次

因为自己懒,不想每次都去弄tableVIew的delegate和dataSource,高大上的说法就是解耦。所以想实现这样的一个功能。(github: https://github.com/yqwanwu/easyTableView
单拿dataSource举例。给tableViewshe设置dataSource为自己。继承接口,然后实现默认的一些操作。但是,默认的操作不可能包含所有情况,所以有时也会自己给这个tableView设置一个新的dataSource,典型的就是在ViewController中设置 tableView.dataSource = self; 问题就来了,这个dataSource会覆盖前面的delegate。只执行新的dataSource中的方法,于是就改成了酱紫:

fileprivate weak var originalDataSouce: UITableViewDataSource?
fileprivate weak var originalDelegate: UITableViewDelegate?


set {
      super.dataSource = self
      originalDataSouce = self.isEqual(newValue) ? nil : newValue        
}      

get {
      return super.dataSource
}

这样写可以在代理方法中先判断originalDataSouce是否实现了当前方法,如果实现了,就用 originalDataSouce的方法,否则直接使用自己写的默认方法。下面举例:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let od = originalDataSouce, !od.isEqual(self) {
            let number = od.tableView(tableView, numberOfRowsInSection: section)
            if number > 0 {
                return number
            }
        }
        
        return dataArray[section].count
    }

当时写完觉得没啥问题了,后来想起来 dataSource 可不止一个方法,如果这样写,新的dataSource就是代码里的 originalDataSouce 实现了一个其他的方法,我默认的实现里没有这个方法,那就悲剧了,这个方法根本不会被执行。因为真实的dataSource,还是tableView的self。一个最简单的解决办法就是 把dataSource中的每个方法都去实现一次,不过,不通用,而且写起来很恶心!
于是想到了 java中的动态代理,顺便就在 百度,google了一下Proxy。了解了有个NSProxy的东西。用这个就可以很好的解决这个问题。可以实现先在新设置的 dataSouce中判断是否有这个方法,没有的话在执行 默认的方法。 NSProxy具体原理请 百度/谷歌 吧,很多文章的。直接贴部分代码:

///BaseProxy.m
@interface BaseProxy ()

@end

@implementation BaseProxy

- (instancetype)initWithObject:(id)obj {
    _obj = obj;
    return self;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    if (_obj) {
        [invocation setTarget:_obj];
        [invocation invoke];
    }
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    if ([_obj isKindOfClass:[NSObject class]]) {
        return [(NSObject *)_obj methodSignatureForSelector:sel];
    }
    return [super methodSignatureForSelector:sel];
}

@end



//TableViewDataSourceProxy.m 部分
@interface TableViewDataSourceProxy : BaseProxy <UITableViewDataSource>
@end

- (instancetype)initWithObject:(id)obj {
    if ([obj conformsToProtocol:@protocol(UITableViewDataSource)]) {
        _objDetail = obj;
    }
    return [super initWithObject:obj];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_objDetail ) {
        NSInteger num = [_objDetail numberOfSectionsInTableView:tableView];
        if (num >= 0) {
            return num;
        }
    }
    return _dataArray.count;
}



//swift中
override var dataSource: UITableViewDataSource? {
        set {
            let dsProxy = TableViewDataSourceProxy(object: newValue)
            super.dataSource = dsProxy
            self.dsProxy = dsProxy
        }
        get {
            return super.dataSource
        }
    }

但是,这样写,需要OC和Swift混编,看上去不是很美观,于是后来再次修改成纯Swift的方式。新建一个类CommonProxy, CommonProxy有两个实例对象都是代理,自己本身不实现代理其他方法,然后通过forwardingTarget去决定执行谁的方法
核心代码是

class CommonProxy: NSObject {
    weak var delegate: AnyObject?
    weak var commonDelegate: AnyObject?
    ///如果是false。当delegate有方法时,不执行commonDelegate对应的方法,如果为true,则直接执行commonDelegate中的方法,这样可以适配一些commonDelegate中的特殊处理
    var shouldInvokeCommonMethod = false
    override func responds(to aSelector: Selector!) -> Bool {
        return delegate?.responds(to: aSelector) ?? false || commonDelegate?.responds(to: aSelector) == true
    }
    
    //路由 把其他类的代理设为自己,自己不实现具体方法
    override func forwardingTarget(for aSelector: Selector!) -> Any? {
        if shouldInvokeCommonMethod, commonDelegate?.responds(to: aSelector) == true {                return commonDelegate
        }
        
        if delegate?.responds(to: aSelector) == true {
            return delegate
        } else if commonDelegate?.responds(to: aSelector) == true {
            return commonDelegate
        }
        
        return super.forwardingTarget(for: aSelector)
    }
    
    /// delegate 真实 的代理,  commonDelegate: 通用代理,这里面实现全部通用逻辑,如果delegate实现了该方法
    init(delegate: AnyObject?, commonDelegate: AnyObject?) {
        super.init()
        self.delegate = delegate
        self.commonDelegate = commonDelegate
    }
}


//使用
//先写两个内部类
private class _CustomTableViewDataSource: CommonProxy, UITableViewDataSource {
        weak var obj: CustomTableView!
        
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return obj.tableView(tableView, numberOfRowsInSection: section)
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            return obj.tableView(tableView, cellForRowAt: indexPath)
        }
    }
    
    private class _CustomTableViewDelegate: CommonProxy, UITableViewDelegate {
     
    }



//改写setter和getter ,delegate 同理
override var dataSource: UITableViewDataSource? {
        set {
            if newValue != nil {
                dataSouceProxy = _CustomTableViewDataSource(delegate: newValue, commonDelegate: self)
                dataSouceProxy.obj = self
            }
            
            super.dataSource = dataSouceProxy
            originalDataSouce = self.isEqual(newValue) ? nil : newValue
        }
        
        get {
            return super.dataSource
        }
    }

以前用OC和Swift混编的版本,已经在之前的一个项目中使用了,没有发生什么意外。新改的纯Swift版本,虽然自己测试过,没发现什么问题。但是确实没实际项目检验,今后如果发现问题,我会及时更新的 

github地址: https://github.com/yqwanwu/easyTableView

相关文章

网友评论

      本文标题:Swift 中实现 Proxy,封装UITableView

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