Core Data - How to fetch an entity with max value property

前端 未结 7 802
误落风尘
误落风尘 2020-12-05 02:06

I have a entity Person with a property personId (personId is unique)

How can I fetch the Person with the max personId?

(I want to f

7条回答
  •  情书的邮戳
    2020-12-05 02:47

    The recommended way is to use Apple Recommended Method NSExpression. I would expect that this would be less expensive than using a sort.If you think about it, with a sort you would have to take all the records sort them and keep the maximum one. With an expression you would just have to read through the list and keep in memory the maximum.

    Here is an example I use with NSDate

    - (NSDate *)lastSync:(PHAssetMediaType)mediaType {
        NSEntityDescription *entity = [NSEntityDescription  entityForName:kMediaItemEntity inManagedObjectContext:self.managedObjectContext];
    
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        fetchRequest.entity = entity;
        fetchRequest.resultType = NSDictionaryResultType;
    
        NSMutableArray *predicates = [NSMutableArray array];
        [predicates addObject:[NSPredicate predicateWithFormat:@"%K=%d", kMediaType,mediaType]];
        [predicates addObject:[NSPredicate predicateWithFormat:@"%K=%d", kMediaProviderType,self.mediaProviderType]];
        NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates: predicates];
        fetchRequest.predicate = predicate;
    
        // Create an expression for the key path.
    
        NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:kSyncTime];
        // Create an expression to represent the function you want to apply
    
        NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:"
                                                                arguments:@[keyPathExpression]];
    
        // Create an expression description using the maxExpression and returning a date.
        NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
        [expressionDescription setName:@"maxDate"];
        [expressionDescription setExpression:maxExpression];
        [expressionDescription setExpressionResultType:NSDateAttributeType];
    
        // Set the request's properties to fetch just the property represented by the expressions.
        fetchRequest.propertiesToFetch = @[expressionDescription] ; // @[kSyncTime];
    
        NSError *fetchError = nil;
        id requestedValue = nil;
    
        // fetch stored media
        NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
        if (fetchError || results == nil || results.count == 0) {
            return [NSDate dateWithTimeIntervalSince1970:0];
        }
        requestedValue = [[results objectAtIndex:0] valueForKey:@"maxDate"];
        if (![requestedValue isKindOfClass:[NSDate class]]) {
            return [NSDate dateWithTimeIntervalSince1970:0];
        }
        DDLogDebug(@"sync date %@",requestedValue);
        return (NSDate *)requestedValue;
    }
    

提交回复
热议问题