我如何以正确的方式从数据库获取最后一条记录?现在我得到了最后的记录,但我无法施展。警告说“从'[Class]'转换为无关类型'Class'总是失败”。是从这个结果中获取属性的其他方法吗?
let _context = DataBaseController.getContext()
let _fetchRequest:NSFetchRequest<Class> = Class.fetchRequest()
do {
let _allElements = try _context.count(for: _fetchRequest)
_fetchRequest.fetchLimit = 1
if _allElements == 1 {
_fetchRequest.fetchOffset = _allElements
} else {
_fetchRequest.fetchOffset = _allElements - 1
}
_fetchRequest.returnsObjectsAsFaults = false
do {
let _result = try DataBaseController.getContext().fetch(_fetchRequest) as! Ping
} catch {
print("Error \(error)")
}
} catch {
print("Error \(error)")
}
提前致谢!
答案 0 :(得分:1)
Core Data fetch总是返回一个托管对象数组
let _result = try DataBaseController.getContext().fetch(_fetchRequest) as! [Ping]
if !_result.isEmpty {
let lastItem to _result[0]
}