Calculating the max value for a core data attribute - NSCFNumber error

前端 未结 3 1428
再見小時候
再見小時候 2020-12-16 15:23

I need to find out the maximum value of an attribute of a core data entity.

I\'m still firmly in the Cocoa learning curve, and this is a simple test app that I\'m us

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 15:45

    I had to solve a similar problem and approached it slightly differently by:

    • querying the entity
    • ordering by the attribute you want
    • limit the fetch results to 1

    The code for this is below. I am querying an entity called 'entityName' and retrieving the max value for the attribute 'sequenceId'.

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *res = [NSEntityDescription entityForName:@"entityName" inManagedObjectContext:managedObjectContext];
    [request setEntity:res];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sequenceId" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [request setSortDescriptors:sortDescriptors];
    [sortDescriptors release];
    [sortDescriptor release];
    
    [request setFetchLimit:1];
    
    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
    [request release];
    if (results == nil) {
        NSLog(@"error fetching the results: %@",error);
    }
    
    NSInteger maximumValue = 0;
    if (results.count == 1) {
        Result *result = (Result*)[results objectAtIndex:0];
        maximumValue =  [result.sequenceId integerValue];
    }
    

提交回复
热议问题