swift 关联属性

Posted by Genie on April 22, 2021
1
2
3
4
5
6
7
8
9
10
private var key: Void?

var title: String? {
        get {
            return objc_getAssociatedObject(self, &key) as? String
        }
        set {
            objc_setAssociatedObject(self, &key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

也可以通过嵌套结构体来定义key

1
2
3
4
5
6
    // 嵌套结构体
       private struct AssociatedKeys {
           static var isShowKey = "isShowKey"
           static var displayNameKey = "displayNameKey"
           static var widthKey = "widthKey"
       }