Sudheer Kumar Palchuri
Sudheer Kumar Palchuri

Reputation: 2954

NSPredicate to fetch records in alphabetical order in CoreData

I am trying to fetch records from an Entity, the records are huge above 5000. So i want to fetch the records with alphabetically sorted(name paramter) instead of sorting with NSSortDescriptor on result array.

Is there any predicate we can place to fetech records alphabetically sorted.

Upvotes: 4

Views: 4454

Answers (3)

Rahul
Rahul

Reputation: 333

Swift 4.0

let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

https://developer.apple.com/documentation/foundation/nssortdescriptor

Upvotes: 6

Jim Tierney
Jim Tierney

Reputation: 4105

Set the NSSortDecriptor within your NSFetchRequest *fetchRequest, like you would with any predicate

[fetchRequest setSortDescriptors:@[[[NSSortSDescriptor alloc] initWithKey:@"name parameter" ascending:YES]]];

This means your request is already sorted like you require as it's being fetched.

As Kaszas has already said, an NSPredicate isn't for sorting, it's for filtering

Hope this helps

Upvotes: 6

Dávid Kaszás
Dávid Kaszás

Reputation: 1977

No, you can't sort an array with an NSPredicate.

The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.

Upvotes: 2

Related Questions