Tidane
Tidane

Reputation: 694

How to sort a fetch in Core Data

I'm doing a fetch of data to show it in a UITableView, I do the fetch but I want to sort them by date of creation or by any sort method.

Here is the method:

-(NSArray *) lesStations {

NSManagedObjectContext *moc = [[AppDelegate sharedAppDelegate]managedObjectContext];

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Station" inManagedObjectContext:moc];

[fetch setEntity:entity];
NSError *error;

NSArray *result = [moc executeFetchRequest:fetch error:&error];

if (!result) {
    return nil;
}

return result;

}

Upvotes: 2

Views: 3985

Answers (3)

jerrylroberts
jerrylroberts

Reputation: 3454

This should work

-(NSArray *) lesStations {

    NSManagedObjectContext *moc = [[AppDelegate sharedAppDelegate]managedObjectContext];

    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity =  [NSEntityDescription entityForName:@"Station" inManagedObjectContext:moc];

    [fetch setEntity:entity];
    NSError *error;

    NSArray *result = [moc executeFetchRequest:fetch error:&error];

    if (!result) {
        return nil;
    }

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:"creationDate" ascending:YES];



    NSArray *sortedResults = [result sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];

    [sort release];

    return sortedResults;

}

Upvotes: 5

graver
graver

Reputation: 15213

You have 2 options: get the results sorted or sort the NSArray with the results:
NSFetchRequest could be set a NSArray of NSSortDescriptor

NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"place" ascending:NO]; //the key is the attribute you want to sort by
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

You can also sort the returned NSArray (see all instance methods of NSArray starting with sortedArray...)
I suggest using the first approach when working with CoreData. The second one is just informative when working with arrays...

Upvotes: 3

BumbleBoks
BumbleBoks

Reputation: 227

You can sort fetch results by setting sortDescriptors for fetch, e.g.

fetch.sortDescriptors = [NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey: ascending: selector:], nil];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];

Upvotes: 0

Related Questions