最後我設法在for
循環檢查第一級子對象,並將它們添加到一個數組(childFolderA)來解決我的問題。
然後我做2個for
環的while
循環內:
- 第一
for
迴路識別所有子文件夾,並把它們添加到一個數組(childFolderB)。
- 然後在第二個
for
循環中掃描此數組,並將所有子對象添加到其他數組(childFolderA)。
- 它會繼續
while
childFolderA或childFolderB數組包含一些東西。
該代碼在函數中。
// Find the list/folder object of the row selected
if let objs = controller.fetchedObjects , objs.count > 0 {
let item = objs[indexPath.row]
// Manage selection for selected object.
if item.selected == 0 || item.selected == 1 {
item.selected = 2
} else {
item.selected = 0
}
var childFolderA: [List] = []
var childFolderB: [List] = []
// Find the 1st level child lists
for child in item.child_lists! {
if item.selected == 0 || item.selected == 1 {
(child as AnyObject).setValue(0, forKey: "selected")
} else {
(child as AnyObject).setValue(2, forKey: "selected")
}
// Add all 1st level child to the array: childFolderA
childFolderA.append(child as! List)
}
// Find all child folders and lists
while (!childFolderA.isEmpty || !childFolderB.isEmpty) {
for child in childFolderA {
if child.type == 1 { // Folder
for child2 in child.child_lists! {
if item.selected == 0 {
(child2 as AnyObject).setValue(0, forKey: "selected") // Set selected circle to 「All」
} else {
(child2 as AnyObject).setValue(2, forKey: "selected") // Set selected circle to 「0」
}
childFolderB.append(child2 as! List)
}
} else { // List
if item.selected == 0 {
child.setValue(0, forKey: "selected") // Set selected circle to 「one list」
} else {
child.setValue(1, forKey: "selected") // Set selected circle to 「0」
}
}
}
childFolderA.removeAll() // Reset childFolderA
for child in childFolderB {
if child.type == 1 { // Folder
for child2 in child.child_lists! {
if item.selected == 0 {
(child2 as AnyObject).setValue(0, forKey: "selected") // Set selected circle to 「All」
} else {
(child2 as AnyObject).setValue(2, forKey: "selected") // Set selected circle to 「0」
}
childFolderA.append(child2 as! List)
}
} else { // List
if item.selected == 0 {
child.setValue(0, forKey: "selected") // Set selected circle to 「one list」
} else {
child.setValue(1, forKey: "selected") // Set selected circle to 「0」
}
}
}
childFolderB.removeAll() // Reset childFolderA
}
childFolderA.removeAll()
childFolderB.removeAll()
它可能不是100%安全,所以讓我知道它是否可以改進。
請顯示您的數據模型。 – sschale
我添加了數據模型。 – Tibo