1

I've saved objects in core data, and I am looking how to fetch those objects as a Dictionary

Here is an example of my code where sections is keys for the dictionary and Company as an array of core data objects.

private var companies = Dictionary<String, Array<Company>>()
private var sections: [String] = ["Pending", "Active", "Pending"]

override func viewWillAppear(_ animated: Bool) {
    let fetchRequest : NSFetchRequest<Company> = Company.fetchRequest()
            let moc = DatabaseController.getContext()
            do {
                let request = try moc.fetch(fetchRequest)
                for case let (index, object) in request.enumerated() {
                   companies[sections[index]]!.append(object)
                }
            } catch let error as NSError {
            print("Could not fetch. \(error), \(error.userInfo)")
        }}

When I am trying to execute my code, I have an error:

enter image description here

fatal error: unexpectedly found nil while unwrapping an Optional value

Could anyone help me with that issue?

1
  • 1
    Fetched objects are returned always as an array, either as [NSManagedObject] or [[String:Any]] depending on the fetch request. Commented Mar 2, 2017 at 10:01

2 Answers 2

1

That error message means that you're force unwrapping an optional that doesn't have a value. In other words you're using ! where you shouldn't. (You should basically never use the force unwrap operator (!).)

Let's look at the line where you do that:

companies[sections[index]]!.append(object)

If we break this down and add the inferred types we have:

let section: String? = sections[index]
let companyArray: Array<Company> = companies[section]!

You're crashing because companies starts off empty, so asking for any of the arrays will return nil. (Actually, I'm not sure how your code is compiling, since you can't subscript into the dictionary with an optional.)

However, if you fix that, we still have a problem because you're using the index of the fetched array to look up the section. If you have more than three companies, that will start to fail.

I suspect you want something like:

for let company in result {
    if var companyArray = companies[company.status] {
        companyArray.append(company)
    } else {
        companies[company.status] = [company]
    }
}

Where status is an invented property on Company that returns a String like "Pending" or "Active".

Sign up to request clarification or add additional context in comments.

1 Comment

I've tried to use your code and I have another issue now. So, I can only save 1 company for each section ("Active" and "Pending"). Is it possible to have multiple companies for the section? My main purpose to create a dictionary is to fill the tableView with sections. @dave
0

I've found the solution, just need to use NSFetchResultController in order to display data in TableView by different sections.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.