美文网首页
iOS-为对象添加不存在的属性并赋值取值

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

作者: 茄子星人 | 来源:发表于2019-06-26 21:56 被阅读0次

    在解析onevcat大神的Kingfisher框架的时候发现运行时的objc_setAssociatedObjectobjc_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)")
    
    

    相关文章

      网友评论

          本文标题:iOS-为对象添加不存在的属性并赋值取值

          本文链接:https://www.haomeiwen.com/subject/clahcctx.html