#CoreDataの操作について
読み込み、追加、更新、削除のサンプルです。
import CoreData を忘れないようにしてください。
##読み込み
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchRequest = NSFetchRequest(entityName: "CoreDataTest")
var coreData:[CoreDataTest] = []
// 読み込み
do {
coreData = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest) as! [CoreDataTest]
} catch let error as NSError {
print(error)
}
##追加
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let coreData = NSEntityDescription.insertNewObjectForEntityForName("CoreDataTest", inManagedObjectContext: appDelegate.managedObjectContext) as! CoreDataTest
coreData.id = 1
coreData.name = "コアデータ"
// コミット
appDelegate.saveContext()
##更新
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchRequest = NSFetchRequest(entityName: "CoreDataTest")
do {
let coreData = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest) as! [CoreDataTest]
for data in coreData {
data.id = 2
data.name = "新コアデータ"
}
} catch let error as NSError {
print(error)
}
// コミット
appDelegate.saveContext()
##削除
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fetchRequest = NSFetchRequest(entityName: "CoreDataTest")
do {
let coreData = try appDelegate.managedObjectContext.executeFetchRequest(fetchRequest) as! [CoreDataTest]
for data in coreData {
appDelegate.managedObjectContext.deleteObject(data)
}
} catch let error as NSError {
print(error)
}
// コミット
appDelegate.saveContext()