核心数据 - 如何获取具有最大值属性的实体

Eya*_*yal 37 iphone core-data objective-c nsfetchedresultscontroller ios

我有一个Person属性的实体personId(personId是唯一的)

如何获取max personId的Person?

(我想取这个人本身而不是财产的价值)

hyp*_*ypt 66

fetchLimit可以1personId降序设置to 和sort by .例如:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];

fetchRequest.fetchLimit = 1;
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"personId" ascending:NO]];

NSError *error = nil;

id person = [managedObjectContext executeFetchRequest:fetchRequest error:&error].firstObject;
Run Code Online (Sandbox Code Playgroud)

  • 如果您没有对要排序的属性的索引,那么这种技术比O(n log n)更昂贵,而不是扫描列表中的最大值O(n),如@Uilleann的回答中所述.也就是说,如果您对要排序的属性有索引,那么这两种技术应该是相同的. (2认同)

Uil*_*ann 22

您需要使用带有NSPredicate的NSFetchRequest来指定您的查询...

改编自Apple的Predicate Progamming指南:

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person"
    inManagedObjectContext:managedObjectContext];
[request setEntity:entity];

request.predicate = [NSPredicate predicateWithFormat:@"personId==max(personId)"];
request.sortDescriptors = [NSArray array];

NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
Run Code Online (Sandbox Code Playgroud)


Rya*_*ner 17

推荐的方法是使用Apple推荐方法 NSExpression.我希望这比使用sort更便宜.如果你想一想,你需要对所有记录进行排序并保持最大值.使用表达式,您只需读取列表并在内存中保留最大值.

这是我与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;
}
Run Code Online (Sandbox Code Playgroud)


jar*_*ora 5

上面使用NSExpression给出的答案是正确的.这是Swift版本.

private func getLastSyncTimestamp() -> Int64? {

let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
request.entity = NSEntityDescription.entity(forEntityName: "EntityName", in: self.moc)
request.resultType = NSFetchRequestResultType.dictionaryResultType

let keypathExpression = NSExpression(forKeyPath: "timestamp")
let maxExpression = NSExpression(forFunction: "max:", arguments: [keypathExpression])

let key = "maxTimestamp"

let expressionDescription = NSExpressionDescription()
expressionDescription.name = key
expressionDescription.expression = maxExpression
expressionDescription.expressionResultType = .integer64AttributeType

request.propertiesToFetch = [expressionDescription]

var maxTimestamp: Int64? = nil

do {

    if let result = try self.moc.fetch(request) as? [[String: Int64]], let dict = result.first {
       maxTimestamp = dict[key]
    }

} catch {
    assertionFailure("Failed to fetch max timestamp with error = \(error)")
    return nil
}

return maxTimestamp
}
Run Code Online (Sandbox Code Playgroud)

其中moc是NSManagedObjectContext.