Wraith
Wraith

Reputation: 501

How reload data with new fetch?

When I loaded my view and called didload, I executed fetch from Core Data. For example, I have 10 records in row, now when I add new row I have from 1 to 11 rows. But after I add a new row, I want to reload table view with only last 10 rows again. How can I call tableView.reloadData() with the same fetch execute like on didload?

 override func viewDidLoad() {
        super.viewDidLoad()

        fetchedResultsController = NSFetchedResultsController(fetchRequest: MInstance.getMessagesList(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
        fetchedResultsController?.delegate = self
        do { try fetchedResultsController?.performFetch() } catch _ {}

        // Refresh table view
        chatTableView.reloadData()
    }

Upvotes: 0

Views: 683

Answers (3)

Johnykutty
Johnykutty

Reputation: 12819

You should implement following delegate methods of NSFetchedResultsController

controllerWillChangeContent(_:)
controller(_:didChangeObject:atIndexPath:forChangeType:newIndexPath:)
controller(_:didChangeSection:atIndex:forChangeType:)
controllerDidChangeContent(_:)

Reference https://developer.apple.com/library/prerelease/ios/documentation/CoreData/Reference/NSFetchedResultsControllerDelegate_Protocol/index.html#//apple_ref/doc/uid/TP40008228-CH1-SW13

Upvotes: 1

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7434

You should use

override func viewDidAppear(animated: Bool) { 

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

         chatTableView.reloadData()

        }

}

then edit

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

        return 10

}

Upvotes: 0

TheRobDay
TheRobDay

Reputation: 521

In your tableView:numberOfRows in section, you can return the minimum of 10 and the amount of items that the FRC has found. Then, your tableView refresh should be limited to 10 rows.

Upvotes: 0

Related Questions