Reputation: 81
I am trying to sort a tableview based on the value of a core data attribute (name) this is the code I have so far but it does not seem to do anything?
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
[self.tableView reloadData];
}
Thanks for any help.
Upvotes: 0
Views: 117
Reputation: 8247
Try to modify your code like this :
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
// Set descriptors
[fetchRequest setSortDescriptors:sortDescriptors];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
You need to set the sort descriptor to your fetchrequest. Supposing the entity "Device" has an attribute "name"
Upvotes: 1