我已经有了CoreData,现在我想将数据保存到iCloud。
在AppDelegate.swift中
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator =
NSPersistentStoreCoordinator (managedObjectModel: self.managedObjectModel)
var storeURL =
self.applicationDocumentsDirectory
.URLByAppendingPathComponent("DeviceCoreData.sqlite")
var storeOptions =
[NSPersistentStoreUbiquitousContentNameKey : "MyDevices"
// NSPersistentStoreRebuildFromUbiquitousContentOption: @(true)
]
//
self.registerCoordinatorForStoreNotifications (coordinator)
var error : NSError? = nil
var store : NSPersistentStore! =
coordinator.addPersistentStoreWithType (NSSQLiteStoreType,
configuration: nil,
URL: storeURL,
options: storeOptions,
error: &error)
if nil == store {
// handle error
}
return coordinator
}()
func registerCoordinatorForStoreNotifications (coordinator : NSPersistentStoreCoordinator) {
let nc : NSNotificationCenter = NSNotificationCenter.defaultCenter();
nc.addObserver(self, selector: "handleStoresWillChange:",
name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
object: coordinator)
nc.addObserver(self, selector: "handleStoresDidChange:",
name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
object: coordinator)
nc.addObserver(self, selector: "handleStoresWillRemove:",
name: NSPersistentStoreCoordinatorWillRemoveStoreNotification,
object: coordinator)
nc.addObserver(self, selector: "handleStoreChangedUbiquitousContent:",
name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
object: coordinator)
}
但是当我构建应用程序时,我收到了一条错误消息
有人可以帮帮我吗?我在这里堆了3天。由于未捕获的异常而终止应用 'NSInvalidArgumentException',原因:' - [Ơn_Giời.AppDelegate handleStoresDidChange:]:发送到实例的无法识别的选择器 0x17668770'
并且
[NSPersistentStoreUbiquitousContentNameKey : "MyDevices"]
此密钥是否正确?我的cloudkit名为iCloud.MyDevices 谢谢你的帮助...
答案 0 :(得分:5)
这一行:
nc.addObserver(self, selector: "handleStoresDidChange:",
name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
object: coordinator)
说当发布该通知时,应该在对象handleStoresDidChange:
(显然是应用代理)上调用名为self
的方法
错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Ơn_Giời.AppDelegate handleStoresDidChange:]: unrecognized selector sent to instance 0x17668770'
表示AppDelegate
没有名为handleStoresDidChange:
的方法。
这就是应用程序崩溃的原因:您已指示通知中心调用不存在的方法。如果您告知通知中心它应该调用方法,则该方法必须存在。您需要创建该方法或告知通知中心调用其他确实存在的方法。