Core Data (Magical Record) + WatchKit Extension + Cocoa Touch Framework
Asked Answered
D

2

9

Here's what I'm up to:

I now have

  • An iPhone app
  • A WatchKit Extension
  • A Cocoa Touch Framework that holds all my shared classes

What I would like to accomplish, is having a persistent storage (Core Data) that is shared between my iPhone app and WatchKit Extension.

So this is what I've done so far

  • Create an app group to have a shared container.
  • Add a Core Data Model (Model.xcdatamodeld) to my Cocoa Touch Framework.
  • Created one Entity in this model
  • Created an NSMangedObject subclass for this entity and added is to my Cocoa Touch Framework
  • Added a DataManager class to my Cocoa Touch Framework

Here what the initializer in my DataManager looks like

public init() {
    let sharedContainerURL: NSURL? = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.company.Project")
    if let sharedContainerURL = sharedContainerURL {
        let storeURL = sharedContainerURL.URLByAppendingPathComponent("Model.sqlite")
        MagicalRecord.setupCoreDataStackWithAutoMigratingSqliteStoreAtURL(storeURL)
        let station: Station? = Station.MR_createEntity()
    }
}

The issue I'm running into

When I init my DataManager from the iPhone app's AppDelegate, no crash occures, but station will be nil.

When I replace the last line with let stations: [Station]? = Station.MR_findAll() as? [Station] the app crashes and shows the following error: A fetch request must have an entity.

I've searched all of SO and Magical Records issues on GitHub, but couldn't find anything to push me in the right direction. All help is much appreciated.

Delanadelancey answered 27/6, 2015 at 23:29 Comment(1)
Whatever you implement, take into account that watchOS 2 extensions actually run on the watch itself. Read the Managing your Data section in the transition guide: developer.apple.com/library/prerelease/watchos/documentation/…Heptachord
D
0

Thanks to Leo Natan's comment I now realize that I should store my core data in both my iPhone app's sandbox as well as in my WatchKit app's sandbox. And not inside a shared container, like I was trying to.

When building for Watch OS 2, I'll be able to use the WatchKit Connectivity Framework to keep both databases in sync. In the meanwhile I could use a solution like MMWormhole to achieve the same thing.

Delanadelancey answered 3/7, 2015 at 9:51 Comment(0)
S
0

I have done my task in my live app with watch and iPhone both. i not needs 2 stores. and MMWormhole is good one to help for instant call back both the sides. also i have handled watch's event by handleWatchKitExtensionRequest.

The sync is proper and works well.

I have followed this forum. - http://www.makeandbuild.com/blog/post/watchkit-with-shared-core-data

Hope this may help you.

Socialization answered 9/7, 2015 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.