开发者

Filtering NSFetchedResultsController results at runtime

What's the best way to implement runtime filtering of Core Data objects using N开发者_如何转开发SFetchedResultsController?

For example, I want to be able to display all Record-entities in a RecordStore-entity, but also filter all Records in a RecordStore for some predefined critera, eg (ANY recordStore.records.count > 0).

I read that changing an NSFetchedResultsController's predicate after it has been created is bad. So should I store the fetched results in an NSArray that I can filter and use that as the UITableView's datasource, or should I create multiple NSFetchedResultsControllers?


You can re-fetch the data when you need to update. If the data itself changed, then you can just call fetch again. If your criteria changed, then set the predicate on your NSFetchedResultsController, and call fetch.


Create the NSFetchRequest instance, update request each time and perform fetch. Delete cache if you are using:

    let shortDescriptor = NSSortDescriptor(key: key, ascending: ascending)


    fetchedResultViewController.fetchRequest.sortDescriptors = [shortDescriptor]

    NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: fetchedResultViewController.cacheName)

    do {
        try fetchedResultViewController?.performFetch()
    } catch let error as NSError {
        print("Error in fetch \(error)")
    }

Read the apple document: https://developer.apple.com/reference/coredata/nsfetchedresultscontroller

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜