2017-04-04 70 views
2
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夫特3.0: 「objc_setAssociatedObject」 問題

  • 在靜態FUNC indexPathForSubRow - > '子行' 計數= 5(線NO:30中附加圖像)
  • 但要indexPath分配子行後.subRow, 'indexPath.subRow' 計數= 0,而不是圖5(線中附加的圖像沒有29 & 31)
  • 在Xcode版本8.2.1 &夫特測試3.0

    任何幫助將不勝感激。

+0

請將實際的代碼發佈到您的問題。閱讀和參考更容易。 – rmaddy

+0

@rmaddy發佈代碼 – Rahul

+1

僅供參考 - 無需爲此使用關聯的對象。 'IndexPath'已經支持任意數量的索引。 'row'和'section'只是用於訪問索引0和1處的值的便利屬性。只需將索引路徑索引2處的'subRow'存儲即可。 – rmaddy

回答

2

IndexPath是一個struct,它不支持關聯對象。

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 ...

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

}