I have a table that is populated using data from CoreData and NSFetchedResultsController. It populates two sections using one attribute having a boolean value. But I want to have the data in each section into two arrays for further processing.
Is there a way to save the data in the two sections generated by the Fetched Results Controller into separate arrays.
i tried to create two predicates using the attribute value used to create the sections using the code:
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var frc: NSFetchedResultsController = NSFetchedResultsController()
func getFetchedResultsController() -> NSFetchedResultsController {
frc = NSFetchedResultsController(
fetchRequest: fetchRequest(),
managedObjectContext: context,
sectionNameKeyPath: "frequent",
cacheName: nil)
return frc
}
//Fetch request of done Items to populate the two sections (Frequent and nonFrequent)
func fetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Item")
let frequentSortDescriptor = NSSortDescriptor(key: "frequent", ascending: false)
let nameSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let predicate = NSPredicate(format: "done == %@", true)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = [frequentSortDescriptor, nameSortDescriptor]
return fetchRequest
}
override func viewDidLoad() {
super.viewDidLoad()
frc = getFetchedResultsController()
frc.delegate = self
frc.performFetch(nil)
frc.fetchRequest.predicate = NSPredicate(format: "frequent == %@", true)
if let freqResults = frc.fetchedObjects as? [Item] {
freq = freqResults
}
frc.fetchRequest.predicate = NSPredicate(format: "frequent == %@", false)
if let nonFreqResults = frc.fetchedObjects as? [Item] {
nonFreq = nonFreqResults
}
println("\(freq.count) Fav and \(nonFreq.count) Non Fav")
}
But the 'println()' at the end prints the two arrays as having 10 counts each. But in reality, 'freq.count' should have 7 and 'nonFreq.count' should have 3 items in them, for the total of 10 items in the two sections combined.
The sections display the correct items. I just can not save those items into arrays.
Is it possible that since the first 'fetchRequst()' has a predicate applied to it already and I'm trying to apply a second predicate on it or what? If that's the case, how can I resolve it?
You have to call performFetch()
before the fetched results controllers's fetchedObjects
will change.
Instead, you might just use a filter.
let frequent = fetchedObjects.filter() { $0.frequent }
let infrequent = fetchedObjects.filter() { !$0.frequent }