我想插入使用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)")
}
}
}
保存實際上是成功還是拋出錯誤?你在哪裏設置託管對象上下文和持久性存儲協調器,他們實際上是否將這些「Persons」實體存儲在正在檢查的文件中? – Jonah