cocoa - 在大型核心数据对象池中查找最大日期的更好方法

标签 cocoa core-data

我有大量的核心日期对象(大约 10000 个),并且根据配置文件执行代码的时间太长: NSDate *maxExternalChangedDate = [代码 valueForKeyPath:@"@max.externalChangedDate"]; 社区知道找到它的更好方法吗?

NSString *rateSheetID = [rateSheetAndPrefix valueForKey:@"rateSheetID"];
NSFetchRequest *requestCodesForSale = [[NSFetchRequest alloc] init];
[requestCodesForSale setEntity:[NSEntityDescription entityForName:@"CodesvsDestinationsList"
                                           inManagedObjectContext:self.moc]];
[requestCodesForSale setPredicate:[NSPredicate predicateWithFormat:@"(%K.carrier.GUID == %@)",relationshipName,carrierGUID]];
NSError *error = nil; 
NSArray *codes = [self.moc executeFetchRequest:requestCodesForSale error:&error];
if (error) NSLog(@"Failed to executeFetchRequest to data store: %@ in function:%@", [error localizedDescription],NSStringFromSelector(_cmd)); 

NSNumber *count = [codes valueForKeyPath:@"@count.externalChangedDate"];
if (count == 0) { 
    [requestCodesForSale release];
    [pool drain], pool = nil;
    return YES;
}
NSDate *maxExternalChangedDate = [codes valueForKeyPath:@"@max.externalChangedDate"];

最佳答案

通过使用 NSFetchRequest 并返回 NSDictionaryResultType,您可以使用 NSExpressionDescription 来生成 max() 和 min() 等函数的结果。

来自 Apple 的示例代码

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"salary"];
NSExpression *maxSalaryExpression = [NSExpression expressionForFunction:@"max:"
                                                  arguments:[NSArray arrayWithObject:keyPathExpression]];

NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"maxSalary"];
[expressionDescription setExpression:maxSalaryExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];

查看此文档以获取更多信息。

Core Data Programming Guide

关于cocoa - 在大型核心数据对象池中查找最大日期的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9194614/

相关文章:

iphone - 为什么我的 xcode 构建总是转到 iPad 模拟器而不是 iPhone 模拟器?

objective-c - cocoa 中的私有(private)方法?

cocoa - 隐藏/显示 NSWindow 中的所有对象 - Cocoa

ios - 循环获取数据时 CoreData 崩溃

ios - 核心数据、iCloud 和两个持久性存储失败

ios - 在 iOS 中使用 Swift 持久化 27000 个节点的 trie 数据树的方法是什么?

core-data - iOS 13.4 CoreData SwiftUI 应用程序在设备上崩溃并显示 "EXC_BREAKPOINT (code=1, subcode=0x1f3751f08)"

cocoa - 超链接在 PDFView 中不起作用(在我的 cocoa 应用程序中)

ios - 核心数据:获取属性的最小值

macos - 以编程方式启动 Mac 的系统偏好设置屏幕 -> 声音