带有Core Data的watchOS 2

Bha*_*gal 3 core-data ios swift apple-watch watchos-2

使用watchOS 1,我的理解是手表扩展程序放在iOS应用程序中,因此您可以为手表应用程序和iOS应用程序使用共享的Core Data持久存储(这是通过使用应用程序组完成的,并且处理iOS应用和观看应用的数据模型的独立框架.)

然而,对于watchOS 2,手表扩展已经移动到手表本身 - 所以它将有自己的持久存储.所以,据我说,我可以直接使用苹果手表上的核心数据而不使用iOS应用程序,但当我创建一个watchOS 2的项目,没有选项可以在你的手表应用程序中使用核心数据.如果我在ExtensionDelegate中添加这些功能:

lazy var applicationDocumentsDirectory: NSURL = {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "finoit.test" in the application's documents Application Support directory.
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1]
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = NSBundle.mainBundle().URLForResource("test", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
            abort()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这些功能永远不会调用,还有其他方法可以在Apple Watch上使用核心数据吗?

或者我在苹果watchOS 2的核心数据概念上走错了路?

谢谢你的建议.

leh*_*058 5

你肯定可以在带有watchOS 2的情况下使用CoreData(我的两个应用程序正在这样做).在创建目标时添加CoreData的选项只是Apple尚未添加的便利复选框.您需要手动添加上面提到的功能并确保自己调用它们,但它的工作方式与在iOS应用程序中的工作方式相同.

请记住,这些数据不会在watchOS和iOS CoreData商店之间同步,因此如果您需要,您需要使用Watch Connectivity自行同步数据.