Search code examples
ioscore-datawatchkitapple-watch

Sharing data between apple watch and iPhone using Core Data


I've made the following DataAccess.swift file to share Core Data between Apple Watch and iPhone app inside a framework. The app in the phone runs perfectly while it shows an error when the apple watch runs.

public  lazy var managedObjectModel: NSManagedObjectModel = {

    let proxyBundle = NSBundle(identifier: "group.com.qburst.toDoListAppGroup")
    **let modelURL = proxyBundle?.URLForResource("DateSaver", withExtension: "momd")!**

    return NSManagedObjectModel(contentsOfURL: modelURL!)!
    }()

For the above code, I get an error "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) " for the marked line in the code.

I've followed this tutorial from GitHub

Can anyone tell me what's wrong with code or the reason why the Watch app fails?


Solution

  • I believe you misunderstood what a bundle identifier is, bundle identifier is not a way to load a bundle from disc, it's a way to identify bundles after it has been loaded.

    In the demo code on Github, the NSManagedObjectModel is retrieved by this way:

    public 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("CoreDataWatch", withExtension: "momd")!
            return NSManagedObjectModel(contentsOfURL: modelURL)!
            }()