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)
在 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/