在解析onevcat大神的Kingfisher
框架的时候发现运行时的objc_setAssociatedObject
和objc_getAssociatedObject
函数可以为不存在的属性赋值取值,奇怪怎么网上的运行时博文怎么都没提到过,清一色的都是分类中为属性添加实现的功能。
...
func getAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer) -> T? {
return objc_getAssociatedObject(object, key) as? T
}
func setRetainedAssociatedObject<T>(_ 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<T>(_ object: Any, _ key: String) -> T? {
return objc_getAssociatedObject(object, key) as? T
}
func setRetainedAssociatedObject<T>(_ 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)")
网友评论