Crocobag
Crocobag

Reputation: 2340

Xcode Project with shared CoreData for iOS & MacOS Targets

A few months ago I started to work on a MacOS Application which required CoreData implementation. Today I am beginning to work on a related iOS application that is based on the same Api, and though relies on the same model. I added my iOS target on my project and I mutualised some classes (by adding them to both targets), including the CoreData Stack:

  1. I added my app.xcdatamodeld on both targets

  2. I added my Object+CoreDataClass.swift & Object+CoreDataProperties.swift on both targets

enter image description here

  1. I modified my ManagedObjectsController to support both iOS and MacOS implementation

enter image description here

by defining the appDelegate for both iOS and OSX, I can access it the same way to get my context let context = appDelegate.persistentContainer.viewContext

It works fine but I was wondering if I am doing this right. Is this the correct way to mutualise access to appDelegate instances between two targets?

Should I use some kind of Protocole & Generic Typing?

Or should I simply build a ManagedObjectController for each target?

Thanks

Upvotes: 1

Views: 287

Answers (1)

Jerry Krinock
Jerry Krinock

Reputation: 5030

Declaring a protocol helps if you have multiple classes which you want to both support common functions. But in this case, UIApplication and NSApplication already support the common functions you need! The problem is that you need access two different global symbols.

One alternative worth considering is: Instead of declaring two classes IosAppDelegate and MacAppDelegate, declare a single class AppDelegate, and move that dirty #if code out of your ManagedObjectsController class and into AppDelegate. Then, this AppDelegate could be used wherever you need a reference to the shared app delegate. This is more than a few places in most projects.

But if you want to get your product out the door asap, and this ManagedObjectsController is the only place you need the shared app delegate, your code is fine.

Upvotes: 1

Related Questions