Swift - 向 Core Data 添加启用 iCloud 的持久存储

Posted

技术标签:

【中文标题】Swift - 向 Core Data 添加启用 iCloud 的持久存储【英文标题】:Swift - Adding an iCloud-Enabled Persistent Store to Core Data 【发布时间】:2014-12-18 12:06:59 【问题描述】:
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let documentsDirectory:NSURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let storeUrl:NSURL = documentsDirectory.URLByAppendingPathComponent("CoreData.sqlite")
var error:NSError?
let coordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: appDel.managedObjectModel)
let storeOptions:NSDictionary = [NSPersistentStoreUbiquitousContentNameKey:"MyAppCloudStore"]
let store:NSPersistentStore = coordinator.addPersistentStoreWithType("NSSQLiteStoreType", configuration: nil, URL: storeUrl, options: storeOptions, error: &error)!
let finaliCloudURL = store.URL

这给我带来了一个错误:

2014-12-18 13:55:59.160 TestApp[1410:314557] CoreData: error: -addPersistentStoreWithType:NSSQLiteStoreType configuration:(null) URL:file:///Users/Bogdan-iMac/Library/Developer/CoreSimulator/Devices/29BD765A-1F4A-4C8A-8EAE-4AA0B1E91918/data/Containers/Data/Application/F19B3C5D-B6AD-4944-B4F3-BBBE4AF36D66/Documents/CoreData.sqlite options:
    NSPersistentStoreUbiquitousContentNameKey = MyAppCloudStore;
 ... returned error Error Domain=NSCocoaErrorDomain Code=134080 "The NSSQLiteStoreType persistent store type does not support iCloud integration." UserInfo=0x79fc9360 NSLocalizedDescription=The NSSQLiteStoreType persistent store type does not support iCloud integration. with userInfo dictionary 
    NSLocalizedDescription = "The NSSQLiteStoreType persistent store type does not support iCloud integration.";

fatal error: unexpectedly found nil while unwrapping an Optional value

我在 Capabilities with Services:Key-value storage 中启用了 iCloud

【问题讨论】:

【参考方案1】:

NSSQLiteStoreType 是一个已定义的常量值。您需要使用NSSQLiteStoreType,而不是@NSSQLiteStoreType"。虽然NSSQLiteStoreType是一个字符串,但它的值不是@"NSSQLiteStoreType"

【讨论】:

let store:NSPersistentStore = coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: storeOptions, error: &error)!

以上是关于Swift - 向 Core Data 添加启用 iCloud 的持久存储的主要内容,如果未能解决你的问题,请参考以下文章

向 Xcode 10 Core Data 生成的文件添加方法

将数据从Core Data加载到Today Widget

Core Data 在 Swift 中将数据添加到关系中

Swift & Core Data - 将实体添加到现有实体

IOS Swift Core Data如何在propertiesToFetch中添加不在propertiesToGroupBy中的字段

Swift 2.1 Core Data - 保存具有一对多关系的数据,但如果已经存在则不要添加异构数据