Howto sort(by: NSManagedObject

I have an array with multiple NSManagedObject’s.
Enery NSManagedObject has an Entity Car.
Tha array name is:Cars.
Declared like: var cars: [NSManagedObject] = []

The entity has multiple attributes.
One of the attributes is carLicensePlate.

I want the array to be sorted on that attribute.

I’ve been looking on the internet for the way to do it but can’t find the right one.
At this time it’s like: cars.sort(by: (NSManagedObject, NSManagedObject) -> Bool )

Now is my question how to do this.
I’m writing in Swift 3.

Thank a lot.

Since you are using NSManagedObject, I assume you are using Core Data. Instead of sorting the array after fetching the records, you could add a sort descriptor to your fetch request. That way your array will already be sorted. Plus it will be more efficient since the sort is done at the database level…

Something like this? (request is your fetch request)

let sort = NSSortDescriptor(key: "carLicensePlate", ascending: true)
request.sortDescriptors = [sort]

Have fun!

1 Like

Thanks for the reply.
I do indeed work with Core Data.
But only for a short time with Swift 3.

A new entry also get sorted the right way.

I can go on now.

Thanks a lot.