iOS swift objc_setAssociatedObject和objc_getAssociatedObject使用

oc中的AssociationsManager在swift中也是可以实现的 使用方法请看下面一个例子

import UIKit

extension UIButton {
    
    func fk_addAction(FKActionBlock:((UIButton)->Void)?){
        //保存block
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_setAssociatedObject(self, key, FKActionBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addTarget(self, action: #selector(itemClick(button:)), for:.touchUpInside)
    }
    
    func fk_addAction(FKActionBlock:((UIButton)->Void)? ,for event:Event){
        //保存block
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_setAssociatedObject(self, key, FKActionBlock, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addTarget(self, action: #selector(itemClick(button:)), for:event)
        
    }
    
    @objc private func itemClick(button:UIButton){
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "fk_addAction:".hashValue)
        objc_getAssociatedObject(self, key)
        if let fkBlock = objc_getAssociatedObject(self, key) as? ((UIButton)->Void){
            fkBlock(button)
        }
    }
}

这里是给UIButton添加一个分类,在分类中给UIButton拓展快速添加点击事件的方法通过block回传,通过objc_setAssociatedObject将block保存,触发点击事件后,通过objc_getAssociatedObject获取之前保存的block发起回调

iOS swift objc_setAssociatedObject和objc_getAssociatedObject使用

上一篇:iOS-MVP架构优化


下一篇:App服务端账号配置和手机账号转换