jailani
jailani

Reputation: 2270

NSPredicate for sorting both attributes?

I have a table in Core Data like:

===============================
student-Id      ||      mark
================================       
      3         ||       20 
      3         ||       10
      3         ||       30
                ||       
      1         ||       30
      1         ||       20
      1         ||       10
                ||      
      2         ||       10
      2         ||       30
      2         ||       20
 ===============================

I can fetch results sorted by student ID easily, but I need the results to show all IDs and marks sorted in ascending order as follows:

===============================
student-Id      ||      mark
===============================       
      1         ||       10
      1         ||       20
      1         ||       30
                ||      
      2         ||       10
      2         ||       20
      2         ||       30

      3         ||       10 
      3         ||       20
      3         ||       30
 ==============================

How can I write a single predicate to fetch the results in the above order?

Upvotes: 1

Views: 1303

Answers (1)

Tim
Tim

Reputation: 60140

I don't believe that you can use a predicate for sorting results in a Core Data fetch request. That responsibility belongs to the sort descriptors that you use in your fetch. Each sort descriptor – an instance of NSSortDescriptor – contains a string key and an order; you specify multiple descriptors to sort by several keys, in the order you provide.

For example, it looks like you want to sort your results first by student-Id, then by mark. In both cases, you want the lowest number first – you're sorting in ascending order. Thus, after creating your Core Data fetch request, you could configure it to have a two-item sortDescriptors array:

// Assuming an existing "fetchRequest":
fetchRequest.sortDescriptors = @[
    [NSSortDescriptor sortDescriptorWithKey:@"student-Id" ascending:YES],
    [NSSortDescriptor sortDescriptorWithKey:@"mark" ascending:YES]
];

From that point on, you can continue your fetch request as usual.

Upvotes: 2

Related Questions