MasterDetailAppテンプレートでCoreDataを使ってテーブルビューのセルの名前をつける条件を保存や更新したいです。
###下記のコードの概要
MasterDetailAppテンプレートのdetailViewControllerからボタンの押した回数に応じてcell_check(enum)のデータが送られてきます。それをCoreDataを使ってセル毎に保存しようと思ってます。
CoreDataの名前はPast_Dataです。中身はenum_CellCheck(Int16) です。
swift
1import UIKit 2import CoreData 3 4enum cell_check: Int { 5 case None = 0 //未選択 6 case Fail = 1 //非クリア 7 case Clear = 2 //クリア 8} 9 10protocol send_any_data { 11 func send_data(data:cell_check) 12} 13 14 15class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, send_any_data { 16 17 var detailViewController: DetailViewController? = nil 18 var managedObjectContext: NSManagedObjectContext? = nil 19 20 21 /**セルのタイトルを変えるか確認するcell_check値**/ 22 var title_changer_checker:cell_check = .None 23 24 /**セルに対するクリアしたかどうかの情報を保存する配列**/ 25 var data_of_cells_cellcheck:[cell_check] = [] 26 27 /**セルの数字を保存**/ 28 var cell_row_num : IndexPath? 29 30 31 override func viewDidLoad() { 32 super.viewDidLoad() 33 34 // Do any additional setup after loading the view. 35 navigationItem.leftBarButtonItem = editButtonItem 36 let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) 37 navigationItem.rightBarButtonItem = addButton 38 /**detailViewController変数にDetailViewControllerクラスを代入**/ 39 if let split = splitViewController { 40 let controllers = split.viewControllers 41 detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController 42 } 43 } 44 45 override func viewWillAppear(_ animated: Bool) { 46 47 var cell:UITableViewCell 48 49 if cell_row_num != nil { 50 cell = tableView.cellForRow(at: cell_row_num!)! 51 52 if title_changer_checker == .Clear { 53 cell.textLabel?.text = "Cleared" 54 data_of_cells_cellcheck[cell_row_num!.row] = .Clear 55 title_changer_checker = .None 56 } 57 58 } 59 60 /**DetailViewControllerから戻った時に呼ばれる**/ 61 clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed 62 super.viewWillAppear(animated) 63 } 64 65 @objc 66 func insertNewObject(_ sender: Any) { 67 let context = self.fetchedResultsController.managedObjectContext 68 let newPastData = Past_Data(context: context) 69 70 // If appropriate, configure the new managed object. 71 newPastData.enum_CellCheck = 0 72 73 // Save the context. 74 do { 75 try context.save() 76 } catch { 77 } 78 } 79 80 // MARK: - Segues 81 82 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 83 if segue.identifier == "showDetail" { 84 if let indexPath = tableView.indexPathForSelectedRow { 85 86 cell_row_num = indexPath 87 88 let object = fetchedResultsController.object(at: indexPath) 89 print(object) 90 //次のコントローラーの定義 91 let next_controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController 92 next_controller.detailItem = object 93 next_controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem 94 next_controller.navigationItem.leftItemsSupplementBackButton = true 95 detailViewController = next_controller 96 next_controller.cell_check_sender = self 97 } 98 } 99 } 100 101 // MARK: - Table View 102 103 override func numberOfSections(in tableView: UITableView) -> Int { 104 return fetchedResultsController.sections?.count ?? 0 105 } 106 107 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 108 let sectionInfo = fetchedResultsController.sections![section] 109 return sectionInfo.numberOfObjects 110 } 111 112 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 113 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 114 let object = fetchedResultsController.object(at: indexPath) 115 116 data_of_cells_cellcheck.insert(.None, at: 0) 117 118 configureCell(cell, withData: object) 119 120 //print("(data_of_cells_cellcheck)") 121 122 return cell 123 } 124 125 override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { 126 // 指定したアイテムを編集可能にしたくない場合はfalseを返します。 127 128 return true 129 } 130 131 override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { 132 if editingStyle == .delete { 133 let context = fetchedResultsController.managedObjectContext 134 context.delete(fetchedResultsController.object(at: indexPath)) 135 136 /**自作部分**/ 137 138 data_of_cells_cellcheck.remove(at: indexPath.row) 139 140 /**自作部分終了**/ 141 142 do { 143 try context.save() 144 } catch { 145 } 146 } 147 } 148 149 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 150 /**セルを選択した時呼ばれる**/ 151 let cell = tableView.cellForRow(at: indexPath) 152 cell?.textLabel?.text = "Chosen" 153 154 } 155 156 func configureCell(_ cell: UITableViewCell, withData Data: Past_Data) { 157 158 cell.textLabel!.text = "UNCLEARED" 159 160 if Data.enum_CellCheck == 0 { 161 cell.textLabel!.text = "UNCLEARED" 162 }else if Data.enum_CellCheck == 1 { 163 cell.textLabel!.text = "Fail" 164 }else if Data.enum_CellCheck == 2 { 165 cell.textLabel!.text = "CLEARED" 166 }else{ 167 cell.textLabel!.text = "「ERROR」 OR 「HUCKED NOW」" 168 } 169 170 } 171 172 // MARK: - Fetched results controller 173 174 var fetchedResultsController: NSFetchedResultsController<Past_Data> { 175 if _fetchedResultsController != nil { 176 return _fetchedResultsController! 177 } 178 179 let fetchRequest: NSFetchRequest<Past_Data> = Past_Data.fetchRequest() 180 181 // バッチサイズを適切な数値に設定します。 182 fetchRequest.fetchBatchSize = 20 183 184 // 必要に応じてソートキーを編集します。 185 let sortDescriptor = NSSortDescriptor(key: "enum_CellCheck", ascending: false) 186 187 fetchRequest.sortDescriptors = [sortDescriptor] 188 189 // 必要に応じて、セクション名のキーパスとキャッシュ名を編集します。 190 // セクション名キーパスのnilは「セクションなし」を意味します。 191 let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") 192 aFetchedResultsController.delegate = self 193 _fetchedResultsController = aFetchedResultsController 194 195 do { 196 try _fetchedResultsController!.performFetch() 197 } catch { 198 } 199 200 return _fetchedResultsController! 201 } 202 var _fetchedResultsController: NSFetchedResultsController<Past_Data>? = nil 203 204 func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 205 tableView.beginUpdates() 206 } 207 208 func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { 209 switch type { 210 case .insert: 211 tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) 212 case .delete: 213 tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) 214 default: 215 return 216 } 217 } 218 219 func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { 220 221 switch type { 222 case .insert: 223 tableView.insertRows(at: [newIndexPath!], with: .fade) 224 case .delete: 225 tableView.deleteRows(at: [indexPath!], with: .fade) 226 case .update: 227 configureCell(tableView.cellForRow(at: indexPath!)!, withData: anObject as! Past_Data) 228 case .move: 229 configureCell(tableView.cellForRow(at: indexPath!)!, withData: anObject as! Past_Data) 230 tableView.moveRow(at: indexPath!, to: newIndexPath!) 231 default: 232 return 233 } 234 } 235 236 func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 237 tableView.endUpdates() 238 } 239 240 func controllerDidChangeContent(controller: NSFetchedResultsController) { 241 // In the simplest, most efficient, case, reload the table view. 242 tableView.reloadData() 243 } 244 */ 245 246 // MARK: -DetailViewControllerクラスからのデータの遷移 247 248 func send_data(data: cell_check) { 249 title_changer_checker = data 250/*******多分、ここでwarning********/ 251 if let cell_num = cell_row_num { 252 let object = fetchedResultsController.object(at: cell_num) 253 object.enum_CellCheck = Int16(title_changer_checker.rawValue) 254 } 255 } 256 257} 258 259
あなたの回答
tips
プレビュー