gpt4 book ai didi

ios - swift 核心数据 : Failed to call designated initializer on NSManagedObject

转载 作者:行者123 更新时间:2023-11-30 13:47:45 32 4
gpt4 key购买 nike

我在使用 Core Data 对象获取数据时遇到问题。

这是用于获取数据的代码

let fetchRequest = NSFetchRequest(entityName: "Country")

var countries = [Country!]()

do {
countries = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [Country!]
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}

这是模型定义

import Foundation
import CoreData

@objc(Country)
class Country: NSManagedObject
{

.....
}

这是模型的扩展

import Foundation
import CoreData

extension Country {

@NSManaged var countryCode: String?
@NSManaged var dialCode: String?
@NSManaged var name: String?

}

我收到以下错误:

CoreData: error: Failed to call designated initializer on NSManagedObject class 'Country' 
fatal error: unexpectedly found nil while unwrapping an Optional value

它在这条线上中断:

countries = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [Country!]

我不确定我是否理解这里的问题所在。有人可以建议吗?

谢谢!

最佳答案

分别去掉这两行中的感叹号即可

var countries = [Country]()

countries = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [Country]

NSManagedObject 对象可以用作非可选对象。

隐式展开的可选类型(带感叹号)强制对象调用具体的初始化程序,该初始化程序必须为 initWithEntity:insertIntoManagedObjectContext:

关于ios - swift 核心数据 : Failed to call designated initializer on NSManagedObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34709727/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com