iOS中NSTimer 避免循环引用

1,Swift
方式一,

import Foundation

private class Block {
    let f : T
    init (_ f: T) { self.f = f }
}

extension Timer {
    static func static_scheduledTimer(timeInterval ti: TimeInterval, repeats: Bool, block: @escaping ()->()) -> Timer {
        return self.scheduledTimer(timeInterval: ti, target: self, selector: #selector(static_blcokInvoke(timer: )), userInfo:Block<()->()>(block), repeats: repeats)
    }
    @objc static func static_blcokInvoke(timer: Timer) {
        if let block = timer.userInfo as? Block<()->()> {
            block.f()
        }
    }
}

方式二

class WeakProxy: NSObject {
    weak var target: NSObjectProtocol?
    
    init(target: NSObjectProtocol) {
        self.target = target
        super.init()
    }
    
    override func responds(to aSelector: Selector!) -> Bool {
        return (target?.responds(to: aSelector) ?? false) || super.responds(to: aSelector)
    }
    
    override func forwardingTarget(for aSelector: Selector!) -> Any? {
        return target
    }
}

暂时记下,明日补下方法分析以及oc版本

你可能感兴趣的:(iOS中NSTimer 避免循环引用)