2017-01-11 96 views
1

這是一個已經工作了很長時間的函數(非常有用於將信息插入到核心數據中)。自從我搬到Swift 3.0後,它遇到了麻煩,在第一行崩潰。我錯過了什麼?核心數據/ Swift 3.0

func insertObject<T:NSManagedObject>(_ entity:T.Type, dico:NSDictionary, notification:String!) -> NSManagedObject? { 
    let entityName = entity.entityName 
    let newItem = NSEntityDescription.insertNewObject(forEntityName: entityName, into:managedObjectContext!) as! T 

    for (key, value) in dico { 
     if let value:AnyObject = value as AnyObject? { 
      (newItem as NSManagedObject).setValue(value, forKey: key as! String) 
     } 
    } 

    do {try managedObjectContext!.save() 
     // We may send a notification: 
     if (notification != nil) 
     {NotificationCenter.default.post(name: Notification.Name(rawValue: notification), object: nil)} 
    } catch let error as NSError {print(error)} 

    return newItem 
} 

身邊我得到這個錯誤在調試器控制檯:

fatal error: Index out of range 

而且我可以看到下面的,與彙編代碼一起:

0x1007811f8 <+116>: bl  0x100674b80    ; function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) ->() to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) ->()]> of generic specialization <preserving fragile attribute,()> of Swift.StaticString.withUTF8Buffer <A> ((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A 
-> 0x1007811fc <+120>: brk #0x1 
+0

什麼確切的錯誤信息(s)給你當碰撞發生? –

+0

此消息:「致命錯誤:索引超出範圍」 – Michel

+0

我剛編輯帖子以提供更多信息,以防萬一這可能有用。 – Michel

回答

0

,如果你想保存核心數據庫中的數據可以使用下面的代碼。

步驟1:聲明這3變量如下提及:

let appDelegate = UIApplication.shared.delegate as! AppDelegate 

var managedContext:NSManagedObjectContext! 

var entity:NSEntityDescription! 

步驟2:可以把在viewdidlode這個代碼(),或在您用於保存數據功能。

managedContext = appDelegate.persistentContainer.viewContext 

entity = NSEntityDescription.entity(forEntityName: "Student", in: managedContext) 

let storeStudent = NSManagedObject.init(entity: entity, insertInto: managedContext) 

     storeStudent.setValue(1, forKey: "rollno") 
     storeStudent.setValue("Anil", forKey: "name") 
     storeStudent.setValue("abc street", forKey: "address") 

     do { 
      try managedContext.save() 
     } catch let error as Error! { 
      print(error.localizedDescription) 
     } 
+0

你的功能不是通用的,這是我的問題的重點。 – Michel

+0

此代碼在swift 3.0中可用。可能你需要不同類型的代碼來將數據存儲在覈心數據中。 – nishee