【问题标题】:objc_getAssociatedObject and Runtime attributesobjc_getAssociatedObject 和运行时属性
【发布时间】:2021-09-01 19:45:26
【问题描述】:

我有以下扩展,用于自动保存/检索 UIImageView 独有的运行时属性:

import UIKit

var imgAttributeKey:String? = nil

extension UIImageView {
    
    var imgAttribute: String? {
        get { return objc_getAssociatedObject(self, &imgAttributeKey) as? String }
        set { objc_setAssociatedObject(self, &imgAttributeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
    }
    
}

这工作正常,但最近再次尝试代码后,getter 总是返回 nil。 Swift 5 版本中是否发生了可能破坏此实现的更改?有什么建议吗?

【问题讨论】:

  • 能否在setter上设置断点,检查XIB解码过程中是否被系统调用?
  • 不,没有调用 setter。
  • 您可以尝试在此声明前添加@objc 吗? @objc var imgAttribute: String?
  • 我得到一个'objc 只能与类成员、@objc 协议和类的具体扩展一起使用'的错误。
  • 你使用的是什么版本的 Xcode?​​span>

标签: swift extension-methods xib swift5


【解决方案1】:

感谢Tarun Tyagi 指出正确的解决方法。

@objc 需要添加到扩展中的属性引用。错误地标记外部属性会导致 objc 只能与类成员、@objc 协议和类的具体扩展一起使用错误。

工作代码如下:

import UIKit

var imgAttributeKey:String? = nil

extension UIImageView {
    
    @objc var imgAttribute: String? {
        get { return objc_getAssociatedObject(self, &imgAttributeKey) as? String }
        set { objc_setAssociatedObject(self, &imgAttributeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
    }
    
}

之所以需要这个,是因为这个项目最初是用 Swift 3 编写的,但从 Swift 4 开始,需要为动态 Objective-C 特性(例如用户定义的运行时属性)提供显式注解 @objc。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2010-11-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多