fetchedResultsController keeps showing the same entity in every row

时间:2015-07-28 16:33:51

标签: ios swift uitableview core-data nsfetchedresultscontroller

I used the code I found on one of popular core data tutorial in the web:

    lazy var fetchedResultsController: NSFetchedResultsController = {
    let medicinesFetchRequest = NSFetchRequest(entityName: "Medicine")
    let primarySortDescriptor = NSSortDescriptor(key: "name.order", ascending: true)

    medicinesFetchRequest.sortDescriptors = [primarySortDescriptor]

    let frc = NSFetchedResultsController(
        fetchRequest: medicinesFetchRequest,
        managedObjectContext: self.managedObjectContext!,
        sectionNameKeyPath: "name",
        cacheName: nil)

    frc.delegate = self

    return frc
    }()

Then I modify the tableView delegate method

   func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: DrugCell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! DrugCell
    var medicine = fetchedResultsController.objectAtIndexPath(indexPath) as! Medicine
    cell.drugName.text = medicine.name
     return cell
    }

The result is that I've got my table view filled with the exact same entity with the same name instead of each entity in corresponding row.

I tried other approach that uses only fetchRequest without fetchResultsController, which actually worked for me, but it's problematic because of reloading tables and other stuff, I suppose fetchedResultsController is the desired pattern when populating tableView.

EDIT:

Figured it out, I implemented tableView data source methods as follows an it worked.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    if let sections = fetchedResultsController.sections {
        return sections.count
    }

    return 0
}

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = fetchedResultsController.sections {
        let currentSection = sections[section] as! NSFetchedResultsSectionInfo
        return currentSection.numberOfObjects
    }

    return 0
}

Anyway, I would be happy to know why this certain implementation makes it possible to work? Before I was just returning costant(for testing) in numberOfRowsInSection method and I had not implemented NumberOfSectionsInTableView. Like this

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

1 个答案:

答案 0 :(得分:0)

Not sure if this is what causes your problem, but it looks like you forgot to return the cell in your "tableview: cellForRowAtIndexpath:" data source method.

Add a return cell after your cell configuration code.