繁体   English   中英

Swift 3.0:“objc_setAssociatedObject”问题

[英]Swift 3.0: “objc_setAssociatedObject” issue

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中测试

    任何帮助将不胜感激。

IndexPath是一个结构,它不支持关联的对象。 您可以通过直接尝试回读设置对象来轻松地在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中的代码有效 ,整个构造仍然不成立:由于结构在传输/分配时被复制(至少通过写入机制上的复制进行修改),因此相关对象将不包含在复制,所以你迟早会丢失这些信息。

然而,不是扩展IndexPath可以扩展NSIndexPath然后工作正常 - 但我想这不是你想要的,因为你想影响从表视图得到的IndexPath ...

根据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)
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM