CoreData: fetch only last elements, not all (iPhon

2020-07-27 03:00发布

问题:

Welcome

i use Core Data to store datas. i need such a method which returns only the last 7 elements of entity. my question is how should i modify this code ( it fetchs all of elements, but i need only last 7)

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trip" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[ NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:NO]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
[request setSortDescriptors:sortDescriptors];  
[sortDescriptor release];  
NSError *error;  
tripArray = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

回答1:

Define last? Core Data does not have a concept of order internally. If you mean by the farthest away based on your distance property then you can do the following:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trip" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[ NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:NO]; 
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
[request setSortDescriptors:sortDescriptors];  
[request setFetchLimit:7];
[sortDescriptor release];  
NSError *error;  
NSArray *tripArray = [managedObjectContext executeFetchRequest:request error:&error];

Note that the addition of the -setFetchLimit: will cause this request to only return 7 results. It will return the "first" 7 based on your sort. So if you want the closest, reverse the ascending: portion of your sort.

-mutableCopy

There is absolutely no point in calling -mutableCopy on the NSArray that is returned from -executeFetchRequest: error:. Adding objects to that NSArray will not add them to Core Data and removing them from that NSArray will not remove them from Core Data. Therefore it has absolutely no value and is just wasteful.

Do you remember where you saw that? I have been trying to track it down for a while now.



标签: core-data