2016-08-17 43 views
2

我想插入使用coredata和swift的簡單數據,下面是我的代碼,但是當我運行這個並打開我的sqlite文件時,我可以看到它沒有數據?任何請幫助出了什麼問題。核心數據文件顯示插入後使用Swift沒有數據

import UIKit 
import CoreData 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
     let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 

     print(documentsPath) 

     self.saveName("John") 

    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func saveName(name: String) { 
     //1 
     let appDelegate = 
      UIApplication.sharedApplication().delegate as! AppDelegate 

     let managedContext = appDelegate.managedObjectContext 

     //2 
     let entity = NSEntityDescription.entityForName("Persons", 
                 inManagedObjectContext:managedContext) 

     let person = NSManagedObject(entity: entity!, 
            insertIntoManagedObjectContext: managedContext) 

     //3 
     person.setValue(name, forKey: "name") 

     //4 
     do { 
      try managedContext.save() 
      //5 
      //people.append(person) 
     } catch let error as NSError { 
      print("Could not save \(error), \(error.userInfo)") 
     } 
    } 

} 
+0

保存實際上是成功還是拋出錯誤?你在哪裏設置託管對象上下文和持久性存儲協調器,他們實際上是否將這些「Persons」實體存儲在正在檢查的文件中? – Jonah

回答

1

嘗試更類似這樣的東西。您擁有的代碼將用於更新與添加。

func saveName(name: String) { 
    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context: NSManagedObjectContext = appDel.managedObjectContext 
    let newItem = NSEntityDescription.insertNewObjectForEntityForName("Persons", inManagedObjectContext: context) as! Persons 
    newItem.person = name 
    do { 
     try context.save() 
    } catch let error as NSError { 

     print("Unresolved error \(error), \(error.userInfo)") 
     abort() 
    } 

} 
+0

我得到未申報類型人員,什麼是人員? – Max

+1

人應該是實體名稱。 – MwcsMac