3
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)

在此处输入图像描述

  • 在静态函数 indexPathForSubRow -> 'subRow' Count = 5 (行号:附图中的 30)

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

  • 在 Xcode 版本 8.2.1 和 Swift 3.0 中测试

    任何帮助将不胜感激。

4

2 回答 2

3

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"
}

即使设置器中的代码可以工作,整个构造仍然不成立:由于结构在传输/分配时被复制(至少在通过写入时复制机制修改时),您的关联对象将不会包含在其中复制,因此您迟早会丢失该信息。

尽管如此,IndexPath可以扩展而不是扩展NSIndexPath,然后可以正常工作-但我想这不是您想要的,因为您想影响从表视图中获得的 IndexPath ...

于 2017-04-04T05:08:06.903 回答
0

根据 maddy 的回答,这是我的 IndexPath 扩展,它添加了一个 subRow 属性。

extension IndexPath {

    init(subRow: Int, row: Int, section: Int) {
        self.init(indexes: [IndexPath.Element(section), IndexPath.Element(row), IndexPath.Element(subRow)])
    }

    var subRow: Int {
        get { return self[index(at: 2)] }
        set { self[index(at: 2)] = newValue }
    }

    var row: Int {
        get { return self[index(at: 1)] }
        set { self[index(at: 1)] = newValue }
    }

    var section: Int {
        get { return self[index(at: 0)] }
        set { self[index(at: 0)] = newValue }
    }

    private func index(at idx: Int) -> IndexPath.Index {
        return self.startIndex.advanced(by: idx)
    }

}
于 2017-05-15T16:45:33.493 回答