Swift CoreData:无法在NSManagedObject上调用指定的初始化程序

时间:2016-01-10 19:16:45

标签: ios swift core-data

我遇到使用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!]

我不确定我明白这里有什么问题。有人可以建议吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

分别删除这两行中的感叹号

var countries = [Country]()

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

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

隐式展开的可选类型(带感叹号)强制对象调用必须为initWithEntity:insertIntoManagedObjectContext:

的具体初始值设定项