apoorv shah
apoorv shah

Reputation: 171

NSSortDescriptor is not working while fetching records from Core Data

I am trying to use NSSortDescriptor in Core Data to fetch my records. Array of modal-objects doesn't get affected by sort descriptor. It gives records in same order.Here is my code:

NSManagedObjectContext *moc=[self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"To_Do" inManagedObjectContext:moc];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"repeatDate" ascending:NO];

NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[sortDescriptor release];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setEntity:entity];
NSError * error = nil;

NSArray *arrEntity = nil;
arrEntity=[moc executeFetchRequest:fetchRequest error:&error];

Upvotes: 2

Views: 2418

Answers (2)

Oleksii
Oleksii

Reputation: 53

I had same problem if I had done like this

fetchRequest.sortDescriptors.append("key")

But if I use

fetchRequest.sortDescriptors = ["key"]

Then it works fine

Upvotes: 0

TechZen
TechZen

Reputation: 64428

The code looks fine and should work. Since it does not there a couple of possible causes.

  1. The unsorted fetch order might be the same as sorted order. This can happen sometimes if you create objects in series and use a a key like a creation date or the like.
  2. Your keys might all have the same value. This can happen if you have a default value.
  3. You have the wrong key or misspelled its name. You should get a complaint but it won't crash if it can't find the key.

Upvotes: 4

Related Questions