2017-01-11 6 views
1

これはかなり長い間働いていた機能(コアデータに情報を挿入するのに非常に便利です)です。私はSwift 3.0に移動して以来、最初の行でクラッシュして問題を抱えています。私は何か見落としてますか?コアデータ/スウィフト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

クラッシュが発生したときにどのようなエラーメッセージが表示されますか? –

+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