zhuber
zhuber

Reputation: 5534

Core Data Sort Fetched Request

I need to fetch my database and order it by id. So for example, i have 2 columns in database, database_id and content. When I NSLOG last line i get all rows of "content" column. But I need to sort those "content" rows based on database_id which is 1,2,3,4,5,6 (ascending). Help ???

 NSFetchRequest *request = [[NSFetchRequest alloc] init];

    NSEntityDescription *ent = [NSEntityDescription entityForName:@"databaseName" inManagedObjectContext:self.managedObjectContext];
    [request setEntity:ent];

    NSSortDescriptor *srt = [NSSortDescriptor sortDescriptorWithKey:@"database_id" ascending:YES];

    [request setSortDescriptors:[NSArray arrayWithObject:srt]];

    NSError *error;
    NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];

    if (!result)
    {
        //error
    }
    NSMutableArray *myArray = [[NSMutableArray alloc] initWithArray:[result valueForKey:@"content"]];

Upvotes: 1

Views: 1549

Answers (1)

Martin R
Martin R

Reputation: 540065

Your database_id is stored as a string and therefore the ids are sorted as strings:

1, 11, 15, 2, 3, 5

The best solution would be to store the database_id as a number (e.g. "Integer 32") in the database.

As a workaround, you can keep your strings, and use a special compare function in the sort descriptor:

NSSortDescriptor *srt = [NSSortDescriptor sortDescriptorWithKey:@"database_id"
                 ascending:YES
                  selector:@selector(localizedStandardCompare:)];

localizedStandardCompare does a "Finder-like" comparison. In particular, strings containing numbers are sorted according to their numerical value.

Upvotes: 3

Related Questions