ios - 将 Core Data 相关代码迁移到 Swift 2

标签 ios swift core-data nsfetchrequest xcode7

我有一些这样的功能:

func getAllEntities() -> [MyEntity]? {

    let fetchRequest = NSFetchRequest(entityName:"MyEntity")

    var error: NSError?
    let fetchedResults = context.executeFetchRequest(fetchRequest) as! [MyEntity]?

    if let results = fetchedResults {
        return results
    }
    else {
            print("Could not fetch \(error), \(error!.userInfo)")
        }
    }

    return nil
}

现在升级到 Swift 2Xcode 7,我收到如下错误:

Cannot downcast from '[AnyObject]' to a more optional type '[MyEntity]?'

Call can throw, but it is not marked with 'try' and the error is not handled

这是在您首次启动 Xcode 7 时执行自动 Swift 代码迁移后进行的操作。在新的 Swift 版本中重写函数的正确方法是什么?

谢谢

编辑:我需要保持与 iOS 7iOS 8 的向后兼容性。

最佳答案

有两个错误:

  • 在 Swift 2 中,executeFetchRequest() 返回一个非可选值。因此您无法将返回值转换为[MyEntity]?。您可以(强制或可选)将其转换为 [MyEntity]
  • executeFetchRequest() 在错误情况下抛出错误,因此它必须 在 do-catch 语句中使用 try 进行调用。

示例:

func getAllEntities() -> [MyEntity]? {

    let fetchRequest = NSFetchRequest(entityName: "MyEntity")
    do {
        let results = try context.executeFetchRequest(fetchRequest) as! [MyEntity]
        return results
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
        return nil
    }
}

强制转换为! [MyEntity] 在这里是可以接受的(就像你的 原始代码)因为您知道实体的类,它是 在核心数据模型检查器中设置。

关于ios - 将 Core Data 相关代码迁移到 Swift 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624216/

相关文章:

ios - Facebook 登录问题 iOS9 + Parse

ios - swift ||从 Superview 动画和删除 subview 时的错误

ios - Swift:自动换行不起作用?即使设置

ios - 对于 Swift 中与闭包相关的代码,我该如何表达我的意思?

ios - 解包核心数据中的可选值时发现 nil

ios - 主观 iPhone/Core 数据设置民意调查

ios - 在 Ipad 上运行应用程序时未加载库

arrays - 从集合中提取数组

ios - 是否有类似分页的代码用于将 JSON 数据保存到 Realmdatabase

cocoa - NSNumberFormatter 和 NSDatePicker 中的核心数据绑定(bind)相关问题