Search code examples
core-dataswift3nsfetchrequest

Accessing entity attribute values fetched from CoreData


I'm having a problem trying to access data in fetched results from CoreData. The data is presented in UITableView, and that displays fine, I am trying to implement an option for filtering the data based on an attribute. This also works fine through NSCompoundPredicate.

The fetch request goes through fine, however I have issues attempting to extract values from one of the attributes of the fetched entity to add them up to present a total cost.

The code for fetching the filtered results:

func attemptFilteredFetch(filter: Array<NSPredicate>) 
{
    let filterCriteria: NSCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: filter)
    let fetchRequest: NSFetchRequest<StoredExpense> = StoredExpense.fetchRequest()
    let dateSort = NSSortDescriptor(key: "dateOfExpense", ascending: false)
    fetchRequest.sortDescriptors = [dateSort]
    fetchRequest.predicate = filterCriteria

    let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    controller.delegate = self
    self.controller = controller

    do
    {            
        try controller.performFetch()            
    } 
    catch 
    {
        let error = error as NSError
        print("\(error)")
    } 
    expenseList.reloadData()
}

So far I have tried a method I found here and similar ones found online, however the app crashes when the attemptFilteredFetch() function is called.

I might be going about this the wrong way, but I expect that I can add the fetch request into an array and iterate through that to get the total value.

Is there a better way? Or is there any way to access the attribute's value on-the-fly?


Solution

  • The issue stemmed from the model being inherited from an older version of Xcode. AFAIK in beta Builds in order to be able to use CoreData NSManagedObject Subclasses had to have been created manually. Since this seems to be redundant now in the final version of Xcode, the manually created model was throwing up random errors. Removing it and cleaning up the code solved the issues I was having.