First, in the data model create a transient attribute (section
). Because it is transient, it is not physically stored and thus not stored in the managed object context.
The section
attribute is shown here:
The entity is shown here:
The class NSManagedObject subclass should have computed 'section' attribute. The NSManagedObject
subclass demonstrating how to accomplish this is shown here:
class Number: NSManagedObject {
@NSManaged var number: NSNumber
var section: String? {
return number.intValue >= 60 ? "Pass" : "Fail"
}
}
Then you must set sectionForKeyPath
in the NSFetchedResultsController initializer to be the transient attribute key in the data model and the cache name if desired.
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: "section", cacheName: "Root")
fetchedResultsController?.delegate = self
fetchedResultsController?.performFetch(nil)
tableView.reloadData()
}
func fetchRequest() -> NSFetchRequest {
var fetchRequest = NSFetchRequest(entityName: "Number")
let sortDescriptor = NSSortDescriptor(key: "number", ascending: false)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
return fetchRequest
}
The result is a UITableViewController
with grades sorted by pass or fail dynamically:
I made a sample project that can be found on GitHub.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…