Swiftで遊ぼう! - 636 - Zoomania 5
- Swiftで遊ぼう!の前書き-> Life-LOG OtherSide
- Swift2.1 & Xcode7.1対応の日本語版アップルチュートリアル!
- Table View実装チュートリアルをXcode7.2.1で解説
- Core Data シンプルチュートリアル
- 私の本業、オフィシャルなブログ-> Life-LOG
ようやくVIewControllerでシンプルにNSManagedObjectContextクラスのプロパティcontextを使えるようになりました。次はNSFetchedResultsControllerクラスのプロパティの扱いです。
実はNSFetchedResultsControllerプロパティはデーターベスに更新が加わるまで必要ないので、遅延格納型プロパティを使っています。非常に現実的な実装法だと思います。私もこのやり方を真似ます。
lazy var fetchedResultsController: NSFetchedResultsController = { let animalsFetchRequest = NSFetchRequest(entityName: "Animal") let primarySortDescriptor = NSSortDescriptor(key: "classification.order", ascending: true) let secondarySortDescriptor = NSSortDescriptor(key: "commonName", ascending: true) animalsFetchRequest.sortDescriptors = [primarySortDescriptor, secondarySortDescriptor] let frc = NSFetchedResultsController( fetchRequest: animalsFetchRequest, managedObjectContext: self.context, sectionNameKeyPath: "classification.order", cacheName: nil) frc.delegate = self return frc }()
表示させたいエンティティのデータを使って、TabelView表示に必要な必須メソッドを埋めてやるだけです。
// MARK: TableView Data Source func numberOfSectionsInTableView(tableView: UITableView) -> Int { guard let sections = fetchedResultsController.sections else { return 0 } return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sections = fetchedResultsController.sections else { return 0 } let currentSection = sections[section] return currentSection.numberOfObjects } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let animal = fetchedResultsController.objectAtIndexPath(indexPath) as! Animal cell.textLabel?.text = animal.commonName cell.detailTextLabel?.text = animal.habitat return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let sections = fetchedResultsController.sections else { return nil } let currentSection = sections[section] return currentSection.name }
これでかなり準備が整いました。まだ最後のステップが残っています。
今日はここまで。