Beginning Core Data - Part 13: Displaying Data by | Ray Wenderlich

This video covers the process of ordering your objects by section.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3444-beginning-core-data/lessons/13

Hi! Running the final project from the materials, and after deleting the app from the simulator and even erasing all contents and settings, I get an error like this after adding a few friends (index and color components values may vary):

Could not fetch. Error Domain=NSCocoaErrorDomain Code=134060 "(null)" UserInfo={reason=The fetched object at index 4 has an out of order section name 'UIExtendedSRGBColorSpace 0 0 1 1. Objects must be sorted by section name'}, ["reason": The fetched object at index 4 has an out of order section name 'UIExtendedSRGBColorSpace 0 0 1 1. Objects must be sorted by section name']

If I relaunch the app it crashes with a similar error and no friend is displayed, I have to delete the app so I can run it again but same story after I add a few friends.

Any idea what could be wrong? Thanks!

@vegetarianzombie Can you please help with this when you get a chance? Thank you - much appreciated! :]

The issue is because the sort order and the section key do not match. The first sort descriptor of a fetch request that is given to a Fetch Request Controller will be used to sort the sections and the sort descriptor in the code first sorts by name and then by eye colour. This was something I overlooked when setting things up - sorry about that.

This is the relevant code in the refresh method:

let sort = NSSortDescriptor(key: #keyPath(Friend.name), ascending:true, selector: #selector(NSString.caseInsensitiveCompare(_:)))
let color = NSSortDescriptor(key: #keyPath(Friend.eyeColor), ascending:true)

request.sortDescriptors = [sort, color]

Replace that with:

let color = NSSortDescriptor(key: #keyPath(Friend.eyeColor), ascending:true)

request.sortDescriptors = [color]

And the code should work correctly for you. All you need to do is make sure that the sort descriptor(s) you pass to the fetch request match how you want the sections to display.

1 Like

It works now, thanks a lot for the quick answer!

Perhaps it could be suitable in the final project to replace:
request.sortDescriptors = [color]
by:
request.sortDescriptors = [color, sort]
so that the elements in every section are sorted by name

That’s something we’ll consider for the next update. Thanks for the heads up!

Man. I slept during this tutorial.
We need engaging stuff please.

It doesn’t appear that the “Final” materials download match what was in the video. For instance, the label.text = "Eye Color: " isn’t there, AFAIK

@bdmoakley Can you please help with this when you get a chance? Thank you - much appreciated! :]