iOS - RunTime(Swift)

RunTime实现存储属性(本质也是一个计算属性)

    //这么写是为了保护域空间
    private struct AssociatedKeys {
         static var isnew = "isnew"
    }
    
    var isNew:Bool{
        get{
            return  objc_getAssociatedObject(self, &AssociatedKeys.isnew) as! Bool
        }
        set{
            objc_setAssociatedObject(self, &AssociatedKeys.isnew, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    
    }

RunTime实现方法交换

   //初始化的时候调用一次
    public override class func initialize(){
        struct Static {
           static var onece:dispatch_once_t = 0
        }
        
        dispatch_once(&Static.onece) {//这里需要这么写
             let m1 = #selector(ViewController.viewDidLoad)
        let m2 = #selector(ViewController.newViewDidload)
        
        let mm1 = class_getInstanceMethod(type(of: self), m1)
        
        let mm2 = class_getInstanceMethod(type(of: self), m2)
        
        
        
        
        method_exchangeImplementations(mm1, mm2)
        }
    }

    //因为和viewDidload交换了,所以系统会调用这个方法,然后调用自己,就相当于调用原来viewDidload
    //一句话就是函数指正的交换,这里可能不是指针交换,而是指针指向内容里面的交换(没深究)
    func ove_viewDidLoad(){
        self.ove_viewDidLoad()
        print("ove_viewdidLoad")
    }

你可能感兴趣的:(iOS - RunTime(Swift))