Search code examples
iosxcodecore-datanspredicatensfetchrequest

Core Data fetching n best results from database


Say we have an entity called products, and this entity has attribute called quality_level. Is there a way to fetch (a single fetch) say 50 best results (using quality_level as condition) from a database that has >50 records... I know that I can set setFetchLimit:50, but that will only return first 50 results not the best ones by quality_level...


Solution

  • Use both NSSortDescriptor and FetchLimit for limited+best results:

    NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"fileName" ascending:YES comparator:^(NSString *obj1, NSString *obj2) {
    
    return [obj1 compare:obj2 options:NSNumericSearch | NSCaseInsensitiveSearch];
    
     }];
    
    [request setSortDescriptors:@[sd]];
    [request setFetchLimit:50];