如何从核心数据获取请求输出中提取最后一个 apiCallsToday
值?
var result: [NSManagedObject]?
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ApiCalls")
fetchRequest.returnsObjectsAsFaults = false
do {
result = try managedContext.fetch(fetchRequest)
print(result!)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
控制台输出:
最佳答案
我不确定您的核心数据对象模型是什么样的,但正如 Sandeep 指出的那样,您将日期存储为字符串。纠正此问题的一种可能性是更新您的模型,以便您的 ApiCalls
具有存储 Date
的 date
属性,而不是 >dateString
属性,存储String
。
要从日期字符串中提取日期,您可以使用DateFormatter
:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let date = dateFormatter.date(from: dateString)
然后,当您创建 ApiCalls
对象时,您将存储实际的 Date
而不是 String
。
如果您想要最新的结果,您可能不想过滤它,而是根据日期键对结果进行排序。您需要将 NSSortDescriptor
添加到 fetchRequest
中。
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
var results: [ApiCalls] = []
let managedContext =
appDelegate.persistentContainer.viewContext
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "ApiCalls")
let sortDescriptor = NSSortDescriptor(key: #keyPath(ApiCalls.date), ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchLimit = 1
do {
results = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
let mostRecentDate = results.first
关于swift - 如何过滤Core Data获取请求结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48570669/