[英]Why is indexPath for section 1 of a tableview starting with a value of [1,0]
我有一個tableView,它分為2個部分。
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
每個部分都有其自己的FetchResultController(FRC)。 這是我的CellForRoatAt函數
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "personCell", for: indexPath) as! PersonTableViewCell
switch(indexPath.section) {
case 0:
print("this is section 0")
let person = positiveFetchedResultsController.object(at: indexPath)
cell.personName.text = person.name
//print("\(person.name!) is the name")
//print("\(person.statement!.count) postive person statement count")
if(person.statement!.count == 0){
print("default")
cell.statementAmount.text = "$0.00"
}
else{
print("\(person.name!) has \(person.statement!.count) statement count")
let amountTotal = person.value(forKeyPath: "statement.@sum.amountOwed") as? Decimal
print("\(amountTotal!) this is the total")
cell.statementAmount.text = String(describing: amountTotal!)
}
case 1:
print("this is section 1")
print("\(negativeFetchedResultsController.object(at: indexPath)) objects fetched")
let person = negativeFetchedResultsController.object(at: indexPath)
cell.personName.text = person.name
print("\(person.name!) is the name")
print("\(person.statement!.count) negative person statement count")
if(person.statement!.count == 0){
cell.statementAmount.text = "$0.00"
}
else{
print("\(person.name!) has \(person.statement!.count) statement count")
let amountTotal = person.value(forKeyPath: "statement.@sum.amountOwed") as? Decimal
print("\(amountTotal!) this is the total")
cell.statementAmount.text = String(describing: amountTotal!)
}
default: cell.personName.text = "hello"
}
第一部分0可以正常工作,而且我應該從打印調用中獲取正確的數據。 但是第1節向我拋出此錯誤並使我的應用程序崩潰。
error: NSFetchedResultsController: no section at index 1 in sections list
CoreData:錯誤:NSFetchedResultsController:在節列表中索引1處沒有節
當我打印indexPath時,我得到的第1部分是[0,0],第1部分是[1,0]。我想,因為我對每個部分使用2個不同的FRC,所以indexPath將從[0,0]開始]。 顯然我錯了,但是我不知道該怎么辦。
FetchedResultsController本身應用於一個表視圖,而不是用於一個表視圖的多個FRC。 因此,一旦您嘗試在第1部分中使用FRC,它就會翻轉出來-它只有一個應為索引0而不是索引1的部分。
有兩種解決方法:
1.偽造第1節的indexPath
這種方法有點麻煩,我不建議這樣做。 但是對於第1部分,您可以將indexPath
設置為indexPath.row, 0
而不是indexPath.row, indexPath.section
(現在是row,1),以使其像FRC一樣在其自己的表視圖中運行。
2:使用FRC初始化程序的sectionNameKeyPath
參數設置不同的部分
此屬性用於區分FRC的各個部分,以幫助支持多個部分。 最好的例子是,如果你有一個名稱字段,你可以使用sectionNameKeyPath
的name
按名稱在你的tableview部分(如地址簿設置)。
看來您正在嘗試對多個FRC進行負/正數操作,如果是這樣的話,那么BOOL
可以讓您知道它是負值還是正值,因此可以將它們分為兩個部分。 這似乎不是最好的方法,因為您要向核心數據模型添加一個新屬性,除了區分各個部分外,不需要添加新屬性,但是有時在核心數據中,它是獲得所需功能的必需條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.