Idan Moshe
Idan Moshe

Reputation: 1533

Equal Core Data statement to SQLite statement (order by ... desc..)

I'm using a statement in sqlite to select specific object from table:

 NSString *statment = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY %@ DESC LIMIT 1", TRAP_TABLE, DISTANCE_TO_CLOSE_POINT];

I want to do the same thing using core data. How should I mix the NSPredicate & NSSortDescriptor in order to do the same?

EDIT: This is what I did, didn't tried it yet:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO selector:@selector(localizedCompare:)];

Upvotes: 0

Views: 140

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

The NSPredicate is like the where clause of a SQL statement. Your example doesn't have a where clause.

In a NSFetchRequest you can add sort descriptors to handle the 'order by'. Also in the NSFetchRequest you can set a fetch limit.

From there you pass the NSFetchRequest to the NSManagedObjectContext and receive your results.

Update 1

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO selector:@selector(localizedCompare:)];

That is overkill in this situation. I am guessing the value you are sorting on is a number which means you don't need localizedCompare: since you are not working with strings. So you can simplify it to:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO];

And if you are in an ARC project, even reduce it down to:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO];

Which can then be thrown directly into the NSFetchRequest:

[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:DISTANCE_TO_CLOSE_POINT ascending:NO]]];

Upvotes: 1

Related Questions