Swiftで遊ぼう! - 629 - CoreDataDemo3 - 11 - NSFetchedResultsController 3
- Swiftで遊ぼう!の前書き-> Life-LOG OtherSide
- Swift2.1 & Xcode7.1対応の日本語版アップルチュートリアル!
- Table View実装チュートリアルをXcode7.2.1で解説
- Core Data シンプルチュートリアル
- 私の本業、オフィシャルなブログ-> Life-LOG
NSFetchedResultsControllerを使った検索結果の扱いを勉強中です。
データベースからデータをロードするメソッド「loadData()」のコードを書いたので、viewDidLoad()メソッド内に加えます。
次はTableViewへの結果の表示ですが、NSFetchedResultsControllerは便利な機能を持っています。変数resultsの内容が変化*1したことを感知するメソッドをデリゲートメソッド*2として持っています。
func controllerDidChangeContent(controller: NSFetchedResultsController) { myTableView.reloadData() }
このメソッドを書いておけば、どのタイミングでTableViewをリロードしてやればいいかなんて考える必要が無くなります。
次にTableViewDataSourceプロトコールのデリゲートメソッドの書き換えです。
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { return results.sections!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.sections![section].numberOfObjects } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = results.objectAtIndexPath(indexPath).name return cell }
そして最後に削除ボタンを押した時の挙動を変更する必要があります。
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let editAction = UITableViewRowAction(style: .Normal, title: "edit"){(action, indexPath) in print("\(indexPath) edited") } editAction.backgroundColor = UIColor.greenColor() let deleteAction = UITableViewRowAction(style: .Default, title: "delete"){(action, indexPath) in let item = self.results.objectAtIndexPath(indexPath) as! Student let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = delegate.managedObjectContext context.deleteObject(item) try! context.save() } deleteAction.backgroundColor = UIColor.redColor() return [editAction, deleteAction] }
NSFetchedResultsControllerを使っていなかった時は、データベースの更新とTableView表示の更新の2つの更新をしなければならなかったのですが、NSFetchedResultsControllerを使えばこの更新作業が楽になります。CoreDataにNSFetchedResultsControllerは必須です。
ということでCoreDataDemo3プロジェクトは終了です。
CoreDataの扱いが面白くなってきました。
今日はここまで。