ios - swift 3.0 : "objc_setAssociatedObject" issue

标签 ios objective-c-runtime swift3

import UIKit
import ObjectiveC

var SubRowObjectKey: String = "subRow"
extension IndexPath {

    var subRow: Int {
        get {
            let subRowObj = objc_getAssociatedObject(self, &SubRowObjectKey)
        
            if subRowObj != nil {
                return (subRowObj as! Int)
            }
        
            return 0
        }
        set {
            let subRowObj = (newValue as NSInteger)
            objc_setAssociatedObject(self, &SubRowObjectKey, subRowObj, .OBJC_ASSOCIATION_RETAIN)
        
        }
    }

    static func indexPathForSubRow(_ subRow: NSInteger, inRow row: NSInteger, inSection section: NSInteger) -> IndexPath {
    
        var indexPath = IndexPath(row: row, section: section)
        indexPath.subRow = (subRow as Int)
        print(subRow)
        print(indexPath.subRow)
        return indexPath
    }
}

let indexPath = IndexPath.indexPathForSubRow(5, inRow: 1, inSection: 2)
print(indexPath.subRow)

enter image description here

  • 在 static func indexPathForSubRow -> 'subRow' Count = 5(附图中的第 30 行)

  • 但是在将 subRow 分配给 indexPath.subRow 之后,'indexPath.subRow' count = 0 而不是 5(附图中的第 29 和 31 行)

  • 在 Xcode 8.2.1 版和 Swift 3.0 中测试

    我们将不胜感激。

最佳答案

IndexPath 是一个结构,不支持关联对象。 您可以通过直接尝试读回 set 对象轻松地在 setter 中检查它:

set {
    let subRowObj = (newValue as NSInteger)
    objc_setAssociatedObject(self, &SubRowObjectKey, subRowObj, .OBJC_ASSOCIATION_RETAIN)
    let subRowObj2 = objc_getAssociatedObject(self, &SubRowObjectKey)
    print(subRowObj2 ?? "nil") // prints "nil"
}

即使 setter 中的代码会起作用,整个构造仍然不成立:因为结构在传输/分配时被复制(至少在修改时通过写入时复制机制),您的关联对象将不会包含在该副本中,因此您迟早会丢失该信息。

尽管如此,您可以扩展NSIndexPath,而不是扩展IndexPath,这样就可以正常工作——但我想这不是您想要的,因为您想影响从 TableView 中获得的 IndexPath...

关于ios - swift 3.0 : "objc_setAssociatedObject" issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198316/

相关文章:

ios - 在没有 "super"关键字的情况下调用 super

Swift 3 不正确的字符串插值与隐式展开的 Optionals

ios - 如何制作一个保持不变的核心数据对象的副本

ios - 如果数据为空,我们如何替换/删除元素

objective-c - 有没有办法从方法结构中获取参数的类类型?

objective-c - ObjC 方法类型编码字符串中的数字是什么?

iOS 应用程序库目录 <uid> 总是会更改

ios - 如何在不使用 segue 的情况下传递数据

ios - 从 Assets 中选择它未显示在 SWIFT 的选项卡栏 Controller 中的图像

php - date_default_timezone_set() 函数