【问题标题】:NSPersistentContainer equivalent for NSPersistentStoreCoordinator.addPersistentStore ofType and optionsNSPersistentContainer 等效于 NSPersistentStoreCoordinator.addPersistentStore 的类型和选项
【发布时间】:2017-07-30 07:45:17
【问题描述】:

苹果在 WWDC2016 上为 iOS10 推出NSPersistentContainer

NSPersistentContainer 类负责加载数据模型,创建托管对象模型,并使用它来创建 NSPersistentStoreCoordinator。

它的初始化真的很简单:

let container = NSPersistentContainer(name: "myContainerName")
container.loadPersistentStores(completionHandler: { /* ... handles the error ... */ })

之前在 CoreData 堆栈创建中,我们设置了 NSPersistentStoreCoordinator 添加了一个 PersistentStore,特别是带有“ofType”和“storeOptions”

let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: [NSPersistentStoreFileProtectionKey:FileProtectionType.complete, NSMigratePersistentStoresAutomaticallyOption: true] as [NSObject : AnyObject])

在这种情况下使用

NSSQLiteStoreType 用于 ofType 参数

[NSPersistentStoreFileProtectionKey:FileProtectionType.complete, NSMigratePersistentStoresAutomaticallyOption: true] 对于选项参数

如何使用NSPersistentContainer 配置这种东西?

【问题讨论】:

    标签: ios core-data swift3 ios10


    【解决方案1】:
    let description = NSPersistentStoreDescription()
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.setOption(FileProtectionType.complete, forKey: NSPersistentStoreFileProtectionKey)
    container.persistentStoreDescriptions = [description]
    

    【讨论】:

    • 你应该得到持久化器的 URL 来创建你的商店描述: let storeURL = container.persistentStoreDescriptions.first!.url!让描述 = NSPersistentStoreDescription(url: storeURL)
    • 编译器抱怨FileProtectionType.complete 并要求我转换为NSObject 可以吗? description.setOption(FileProtectionType.complete as NSObject, forKey: NSPersistentStoreFileProtectionKey)
    【解决方案2】:

    (发布单独的答案,因为对最后一个答案的评论太长了)

    以下代码对我有用:

    let container = NSPersistentContainer(name: "MyApp")
    
    let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
    let url = storeDirectory.appendingPathComponent("MyApp.sqlite")
    let description = NSPersistentStoreDescription(url: url)
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.setOption(FileProtectionType.completeUnlessOpen as NSObject, forKey: NSPersistentStoreFileProtectionKey)
    container.persistentStoreDescriptions = [description]
    
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2018-01-17
      相关资源
      最近更新 更多