1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftについての覚書4

Posted at

#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()
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?