斯威夫特抱怨未申报类型,但似乎并没有成为问题

问题描述 投票:-2回答:1

我试图获取核心数据的记录。

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的更好吗?谢谢,抱歉的咆哮。

arrays swift fetch typeerror
1个回答
0
投票

你强制转换为对象的类型,而不是对象为对象。

例:

let a = b as! [String]

并不是:

let a = [String]()
let c = b as! a

解决方案1:

更改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)")
    }
}

解决方案2:

如果你想这个方法即使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)
}

溶液的选择,取决于你的设计和要求。

© www.soinside.com 2019 - 2024. All rights reserved.