iOS runtime Extension里添加属性

2019-08-23 17:56:47 浏览数 (1)

关联属性

创建Person类,然后在扩展文件里面添加address属性。

代码语言:javascript复制
class Person: NSObject {
    @objc private var name: String = ""
    @objc private var gender: String = ""
  
}


var ADDRESSKEY = "ADDRESSKEY"
extension Person {
    /// Extension里面添加属性
    var address: String? {
        set {
            objc_setAssociatedObject(self, &ADDRESSKEY, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
        get {
            return objc_getAssociatedObject(self, &ADDRESSKEY) as? String
        }
    }
}
p.address = "YiShanLu No.404"
debugPrint(p.address!)
=================print=======================
"YiShanLu No.404"

0 人点赞