swift3.0 Runtime 增加属性

前端之家收集整理的这篇文章主要介绍了swift3.0 Runtime 增加属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

贡献者:赵大财
博客:https://my.oschina.net/zhaodacaiGitHub:https://github.com/dacaizhao
邮箱: dacai_zhao@163.com QQ:327532817
=============================
先附带一个OC版的http://www.jb51.cc/article/p-pkwqrtdq-boo.html

class DCRuntime: NSObject {

    var name:String = ""
    
    func makeMoney()   {
        print(self.name,self.job ?? "","很多很多swift")
    }
}
extension DCRuntime {
    struct RuntimeKey {
        static let job = UnsafeRawPointer.init(bitPattern: "job".hashValue)
    }
    
    var job: String? {
        set {
            objc_setAssociatedObject(self,DCRuntime.RuntimeKey.job,newValue,.OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
        
        get {
            return  objc_getAssociatedObject(self,DCRuntime.RuntimeKey.job) as? String
        }
    }
}
class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let dacai = DCRuntime()
        dacai.job = "ios"
        dacai.name = "zhaodacai"
        dacai.makeMoney()
    }
}
原文链接:https://www.f2er.com/swift/322283.html

猜你在找的Swift相关文章