Search code examples
iosiphonexcodecore-datansmanagedobjectcontext

Core Data: get lowest value of an attribute


Still somewhat new to Core Data and am stuck on a problem. I have an int property in a managed object called index. I need to loop through all managed objects and determine the highest index value. I chose descending in my sort descriptor so that I can access the array object at index 0. I know this should be simple, but here is my current code:

+(NSInteger)getHighIndexNumber{
    NSManagedObjectContext *context = [[FavesDataModel sharedDataModel] mainContext];
    NSFetchRequest *fetchReq = [[NSFetchRequest alloc] init];

    NSSortDescriptor *sortByIndex = [[NSSortDescriptor alloc] initWithKey:@"index" ascending:NO];
    [fetchReq setSortDescriptors:[NSArray arrayWithObject:sortByIndex]];

    NSEntityDescription *entity = [NSEntityDescription entityForName:[Favorite entityName] inManagedObjectContext:context];
    [fetchReq setEntity:entity];

    return ???
} 

Any suggestions? Thanks!


Solution

  • Your code looks OK, so just execute the fetch request:

    NSError *error;
    NSArray *objects = [context executeFetchRequest:fetchReq error:&error];
    if (objects == nil) {
        // An error occurred, report error and return nil?
        NSLog(...);
        return nil;
    } else if ([objects count] == 0) {
        // No object found, return nil?
        return nil;
    } else {
        // At least one object found, return the first one:
        return objects[0];
    }
    

    Note that since you need only the first element, you can improve the performance by setting

    [fetchReq setFetchLimit:1]