无法在NSManagedObject上调用指定的初始值设定项

时间:2016-09-20 08:56:18

标签: ios swift core-data

我有一个NSManagedObject类,我用它来保存和检索核心数据。

class Nickname: NSManagedObject {

func saveData(addressDetails:[String:AnyObject]){
    var isDataSaved = false
    let address = NSEntityDescription.insertNewObjectForEntityForName("Nickname",
                                    inManagedObjectContext: appDelegate.managedObjectContext) as! Nickname
    if let addressString = addressDetails["address"] as? String{
        if let addressNickName = addressDetails["nickname"] as? String{
            if let addressID = addressDetails["id"] as? String{
                address.address = addressString
                address.nickname = addressNickName
                address.addressID = addressID
                do{
                    try appDelegate.managedObjectContext.save()
                    isDataSaved = true
                }
                catch{
                    print(error)
                }
            }
        }
    }
    if !isDataSaved{
        NSLog("Data not saved in core data. Check Nickname ManagedObject class")
    }
}

func getData(nickName:String)->String?{
    let fetchRequest = NSFetchRequest(entityName: "Nickname")
    fetchRequest.predicate = NSPredicate(format: "nickname = %@", nickName)
    fetchRequest.returnsObjectsAsFaults = false
    var result : [AnyObject]!
    do{ result = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest)}
    catch { print(error)}
    let requiredData = result[0] as? Nickname
    return  requiredData != nil ? (requiredData!.address) : (nil)
}

}

在viewController中,我正在执行save和fetch,我正在创建一个像这样的对象

    let table = Nickname()
    let params = ["address":"aasdadad","nickname":"asdadadadad","id":"69"]
    table.saveData(params)
    let data = table.getData("asdadadadad")
    print(data)

但我一直收到错误

CoreData: error: Failed to call designated initializer on NSManagedObject class 'XXXX.Nickname'

我知道它正在发生,因为我没有以正确的方式创建一个对象。我一直在寻找并找不到解决方案。

注意:SO中有很多关于同一错误的问题。我尝试了所有建议的解决方案,但仍未找到解决此问题的方法。

0 个答案:

没有答案