2017-07-01 16 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