iOS-为对象添加不存在的属性并赋值取值

在解析onevcat大神的Kingfisher框架的时候发现运行时的objc_setAssociatedObjectobjc_getAssociatedObject函数可以为不存在的属性赋值取值,奇怪怎么网上的运行时博文怎么都没提到过,清一色的都是分类中为属性添加实现的功能。

...
func getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> T? {
    return objc_getAssociatedObject(object, key) as? T
}

func setRetainedAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: T) {
    objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
...
var placeholderKey: Void?
setRetainedAssociatedObject(self, &placeholderKey, "helloworld")
let str: String = getAssociatedObject(self, &placeholderKey) ?? ""
print(str)
...
func getAssociatedObject(_ object: Any, _ key: String) -> T? {
    return objc_getAssociatedObject(object, key) as? T
}

func setRetainedAssociatedObject(_ object: Any, _ key: String, _ value: T) {
    objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
...

setRetainedAssociatedObject(self, "sob", "helloworld")
let str: String = getAssociatedObject(self, "sob") ?? ""
print("print:\(str)")

你可能感兴趣的:(iOS-为对象添加不存在的属性并赋值取值)