我试图获取核心数据的记录。
func fetchOrg() {
var **internalOrganization** = [InternalOrganizationMO]() //NSManagedClass
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "InternalOrganization")
fetchRequest.returnsObjectsAsFaults = false
do {
let result = try managedObjectContext.fetch(fetchRequest) as **internalOrganization** **////Compiler flags Error here**
} catch {
fatalError("Failed to fetch internal organization \(error)")
}
}
InternalOrganizationMO
是对应于对象模型ManagedObject
类,它似乎清楚,我认为internalOrganization
声明为那些对象的数组,所以标记误差似乎是关闭。我的理解是,这是应该的获取目标对象的类型,但我肯定是学习曲线在这里。
难道抓取需要在一个类型,而不是一个数组为目标 - 因此,我的没有提供一个名为类型的投诉?如果是,我,我只是应该提供ManagedObject
?如果是这样,如何在地球上我确定有多少返回的记录?
这真的是比只使用接口SQLite的更好吗?谢谢,抱歉的咆哮。
你强制转换为对象的类型,而不是对象为对象。
例:
let a = b as! [String]
并不是:
let a = [String]()
let c = b as! a
更改NSFetchRequest<NSFetchRequestResult>
指定类型是明确InternalOrganizationMO
,就像这样:
NSFetchRequestResult<InternalOrganizationMO>
这fetchRequest
现在有正确的相关类型InternalOrganizationMO
并使用相应的返回此类型的对象。
然后,您就不用再强制转换result
和下面的代码应该只是罚款:
func fetchOrg() {
let fetchRequest = NSFetchRequest<InternalOrganizationMO>(entityName: "InternalOrganization")
do {
let internalOrganization = try managedContext.fetch(fetchRequest)
/*
internalOrganization will be of type [InternalOrganizationMO]
as that is the return type of the fetch now.
*/
//handle internalOrganization here (within the do block)
print(internalOrganization.count)
}
catch {
fatalError("Failed to fetch internal organization \(error)")
}
}
如果你想这个方法即使fetchRequest
尝试或强制转换失败,那么你可以做这方面的工作:
func fetchOrg() {
var internalOrganization = [InternalOrganizationMO]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "InternalOrganization")
do {
internalOrganization = try managedContext.fetch(fetchRequest) as? [InternalOrganizationMO]
/*
You ofcourse wouldn't want the above optional binding to fail but even if it
does, atleast your method can stay consistent and continue with an empty array
*/
}
catch {
fatalError("Failed to fetch internal organization \(error)")
}
//handle internalOrganization here
print(internalOrganization.count)
}
溶液的选择,取决于你的设计和要求。