Soumya Chakraborty
Soumya Chakraborty

Reputation: 93

how do i set UItableView datasource from CoreData relationship.

My coredata relationship fetch request returns NSSet objects. How can I set this data for a tableview datasource since NSset in unordered set. I can convert the NSSet to NSArray , but will it return the data in same order.

Upvotes: 1

Views: 237

Answers (1)

user212514
user212514

Reputation: 3130

Apple is clear that "The order of the objects in the array is undefined." So I would expect it could change.

I would recommend that you store the allObjects array into an instance variable and use that to implement numberOfSectionsInTableView() and the other datasource methods.

You could also store your NSFetchedResultsController in an instance variable and safely use it like:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rows = 0
    if self.fetchedResultsController!.sections!.count > 0 {
        let sectionInfo = getSectionInfo(section)
        rows = sectionInfo!.numberOfObjects
    }
    return rows
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    let sectionInfo = getSectionInfo(section)
    return sectionInfo!.name
}

func getSectionInfo(section: Int) -> NSFetchedResultsSectionInfo? {
    var sections: [AnyObject] = self.fetchedResultsController!.sections!
    if section < sections.count {
        let x = sections[section] as! NSFetchedResultsSectionInfo
        return x
    }
    return nil
}

override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
    return self.fetchedResultsController!.sectionForSectionIndexTitle(title, atIndex: index)
}

override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    return self.fetchedResultsController!.sectionIndexTitles
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("YourCellIdentifier")! as UITableViewCell

    // Use your own NSManagedObject class here...mine is Category
    let category = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Category
    return cell
}

Personally I have coded all of the above methods in a base class that I reuse so I can just implement the cellForRowAtIndexPath() in each new table view. I posted a copy on github in case it might be useful for someone else.

Upvotes: 0

Related Questions