2017-07-01 17 views
0

我有一個數組最佳數據源配置爲UITableView的使用節

secInfArr = [] 
    let secInf1 = SecInfObj.init() 
    secInf1.selected = true 
    secInf1.itemName = "item1" 
    secInf1.sectionName = "section3" 
    secInfArr.append(secInf1) 

    let secInf2 = SecInfObj.init() 
    secInf2.selected = true 
    secInf2.itemName = "item1" 
    secInf2.sectionName = "section1" 
    secInfArr.append(sectionInfo2) 

    let secInf3 = SecInfObj.init() 
    secInf3.selected = true 
    secInf3.itemName = "item1" 
    secInf3.sectionName = "section1" 
    secInfArr.append(secInf3) 

    let secInf4 = SecInfObj.init() 
    secInf4.selected = false 
    secInf4.itemName = "item1" 
    secInf4.sectionName = "section2" 
    secInfArr.append(secInf4) 

,我想創建在該節tableView,所有這些內容都是由sectionName財產分組,和所有的itemName小號按字母順序排序。

到目前爲止,我正在做我認爲效率低下的事情。我正在對數組中的sectionName屬性執行Distinct操作,然後使用它來命名節並對它們進行計數。之後,在CellForRowAtIndexPath方法中,我只需使用sectionName過濾數組,然後添加單元格。

我也想過使用NSFetchedResultsController,但我不認爲這會是一個好主意,因爲數據本質上並不是持久的,因此不需要在managedObject表單中。

在這種情況下,爲分組表視圖構造數據的理想方式是什麼?

回答

0

我建議根據部分將它們分開放入不同的數組中。在數據源中調用要容易得多,特別是對於numberOfRowsInSectioncellForRowAt方法。由於UITableView通過其索引直接訪問數組,所以UITableView也很容易獲取每個單元的數據。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    if section == 0 { 
     return items0.count 
    } 
    else if section == 1 { 
     return items1.count 
    } 
    return 0 
} 

或者也可以類似如下。如果所有的2單獨成items[0] ... items [n]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return items[section].count 
} 
1

我建議例如面向對象的溶液與name屬性一個結構和items陣列,這裏以一般的形式。

struct Section<T> { 

    let name : String 
    var items = [T]() 

} 

如果items陣列被頻繁突變使用class而非struct採取引用語義的優點。

當填充數據源時,將SecInfObj對象分配給相應的Section實例。

的項目可以很容易進行排序,你可以宣佈你的數據源

var data = [Section<SecInfObj>]() 

numberOfRows回報

return data[section].items.count 

你被索引路徑的部分與

let section = data[indexPath.section] 

和那麼與

let items = section.items[indexPath.row] 
+0

感謝Vadian的迴應。 基本上,我無法控制數據,我以我從Web服務描述的形式接收數據。什麼是最有效的方式,沒有嵌套循環,將它們轉換爲所述結構? – NSFeaster