T. Christiansen
T. Christiansen

Reputation: 1038

Core Data Relation: Filter and Sort

In my coredata I have two entities (Profile, Photo). Profile has a toMany relationship (photos) to Photo.

I'm able to access the Photos:

// all
let photos = profile.photos?.allObjects

// sorted
let photos = profile.photos?.sortedArray(using: [NSSortDescriptor(key: "ordering", ascending: true)])

// filtered
let photos = profile.photos?.filtered(using: NSPredicate(format: "type = 'x'"))

Is there an easy way to combine filtering and sorting using the relation or do I have to crate a separate NSFetchRequest?

Upvotes: 1

Views: 1965

Answers (2)

T. Christiansen
T. Christiansen

Reputation: 1038

Thanks Toldy, this works for me:

var photos = profile.photos?.sortedArray(using: [NSSortDescriptor(key: "ordering", ascending: true)]) as! [Photo] as NSArray
photos = photos.filtered(using: NSPredicate(format: "type = 'x'")) as NSArray

Upvotes: 0

prabhu
prabhu

Reputation: 782

As per my understanding, your question is not related to core data, it is related to sorting and filtering on same array, so please try following code

let photos = profile.photos?.allObjects
let result = photos
                .filter { $0.type == "x" }
                .sort { $0.ordering < $1.ordering }

As another way, if you don't want to add explicit filter and sorting on result array, then you can create a fetch request, and add predicate with sort descriptor, so you will get expected result.

Upvotes: 1

Related Questions