LoginSignup
3

More than 3 years have passed since last update.

NSPersistentContainerで、CoreDataをオンメモリで使う

Last updated at Posted at 2019-09-25

いっつも忘れちゃうのでメモ。
iOS 10からNSPersistentContainerでCoreDataを使うのがデファクトスタンダードになってますが、
その時に、CoreDataの機能そのままオンメモリでデータベースファイルとして保存せず使いたい場合がありますよね。

その時は、NSPersistentContainerのpersistentStoreDescriptionsに対して
NSInMemoryStoreTypeのtypeを持ったNSPersistentStoreDescriptionを与えればよいです。
何も設定しない場合、SQLiteファイルに保存する形でCoreDataを扱います。

        let container = NSPersistentContainer(name: "appname")
        let persistentStoreDescription = NSPersistentStoreDescription()
        persistentStoreDescription.type = NSInMemoryStoreType
        container.persistentStoreDescriptions = [
            persistentStoreDescription
        ]
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

# 追記
URLにURL(fileURLWithPath: "/dev/null") を設定することでもメモリ上での利用が可能みたいです

参考 https://developer.apple.com/videos/play/wwdc2018/224/?time=1838

        container.persistentStoreDescriptions[0].url = URL(fileURLWithPath: "/dev/null")

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
3