Swiftで遊ぼう! on Hatena

あしたさぬきblogでやってた初心者オヤジのiOSプログラミング奮闘記がHatenaに来ました

Swiftで遊ぼう! - 636 - Zoomania 5

ようやく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
}

これでかなり準備が整いました。まだ最後のステップが残っています。

今日はここまで。