您可以实现这一点,假设您将一个年份数组传递给一个算法,并期望以字典的形式得到一个结果,每一年您作为一个对象的键传入,该对象对应于最那年最近的车。
即:
let years : [Int] = [2000, 2005]
//The ideal method:
func mostRecentFor<T>(years: [Int]) -> [String:T]
假设您只使用少量搜索年份,并且您的数据库中有少量汽车,您不必担心线程问题。否则,对于这种方法,您必须使用并发或专用线程进行提取以避免阻塞主线程。出于测试目的,您不需要这样做。
要做到这一点,您可以使用以下方法。
首先,应该像其他答案所建议的那样在年份上使用数字谓词。
为此,您将使用 NSPredicate 的日期格式:
NSPredicate(format: "date == %@", year)
因此,您的模型应该将年份作为参数,将实际的 nsdate 作为另一个参数。然后,您将使用设置为 1 的 fecthLimit 参数,并将 sortDescriptor 应用于 nsDate 键参数。后两者的组合将确保只返回给定年份的最年轻或最旧的值。
func mostRecentFor(years: [Int]) -> [String:Car] {
let result : [String:Car] = [:]
for year in years {
let request: NSFetchRequest<CarModel> = CarModel.fetchRequest()
request.predicate = NSPredicate(format: "date == %@ AND name != nil", year)
request.fetchLimit = 1
let NSDateDescriptor: let sectionSortDescriptor = NSSortDescriptor(key: "nsDate", ascending: true)
let descriptors = [NSDateDescriptor]
fetchRequest.sortDescriptors = descriptors
do {
let fetched = try self.managedObjectContext.fetch(request) as
[CarModel]
guard !fetched.isEmpty, fetched.count == 1 else {
print("No Car For year: \(year)")
return
}
result["\(year)"] = new[0].resultingCarStruct //custom parameter here.. see bellow
} catch let err {
print("Error for Year: \(year), \(err.localizedDescription)")
}
}
return result
}
我们在这里使用升序设置为true,因为我们希望第一个值,即由于fetchLimit值为1而实际返回的值,是该年份最早的汽车,或者是最小的汽车nsDate 键的时间戳。
这应该为您提供一个用于小型数据存储和测试的简单获取查询。此外,创建一个方法或参数来将 CarModel 解释为其对应的 Car 结构体可以更简单地从 CD 转到内存对象。
所以你会像这样搜索你的汽车:
let years = [1985, 1999, 2005]
let cars = mostRecentFor(years: years)
// cars = ["1985": Car<year: 1985, name: "Chevrolet", nsDate: "April 5th 1985">, "1999" : Car<year: 1999, name: "Toyota Corolla", nsDate: "February 5th 1999">]
// This examples suggests that no cars were found for 2005