我在使用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:
的具体初始化程序