Swift抱怨类型未声明,但这似乎不是问题

时间:2019-02-05 05:09:20

标签: arrays swift fetch typeerror

我正在尝试获取Core Data中的记录。

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被声明为这些对象的数组,因此标记的错误似乎是关。我的理解是,这应该是获取的目标,但是我绝对是这里的学习曲线。

是不是需要将获取的对象定位为 Type 而不是 array -因此,关于我未提供命名类型的投诉?如果是这样,我是否只想提供ManagedObject?如果是这样,我到底该如何确定返回了多少记录?

这真的比仅使用SQLite接口好吗? 谢谢,很抱歉。

1 个答案:

答案 0 :(得分: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)
}

解决方案的选择取决于您的设计和要求。