简单的demo演示Core Data是如何工作的
Core Data存储数据
func saveName(name: String) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
person.setValue(name, forKey: "name")
do {
try managedContext.save()
}catch {
print("Error")
}
people.append(person)
}
Core Data读取数据
override func viewWillAppear(animated: Bool) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Person")
var fetchRequests = [NSManagedObject]()
do {
fetchRequests = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
}catch {
}
self.people = fetchRequests
}```
网友评论