简体   繁体   English

带有共享 CoreData 的 Xcode 项目,用于 iOS 和 MacOS 目标

[英]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.几个月前,我开始研究需要 CoreData 实现的 MacOS 应用程序。 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.今天我开始研究一个相关的 iOS 应用程序,它基于相同的 Api,但依赖于相同的模型。 I added my iOS target on my project and I mutualised some classes (by adding them to both targets), including the CoreData Stack:我在我的项目中添加了我的 iOS 目标,并共享了一些类(通过将它们添加到两个目标中),包括 CoreData 堆栈:

  1. I added my app.xcdatamodeld on both targets我在两个目标上都添加了我的app.xcdatamodeld

  2. I added my Object+CoreDataClass.swift & Object+CoreDataProperties.swift on both targets我在两个目标上都添加了我的Object+CoreDataClass.swiftObject+CoreDataProperties.swift

在此处输入图片说明

  1. I modified my ManagedObjectsController to support both iOS and MacOS implementation我修改了我的ManagedObjectsController以支持 iOS 和 MacOS 实现

在此处输入图片说明

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通过为 iOS 和 OSX 定义appDelegate ,我可以以相同的方式访问它来获取我的上下文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?这是在两个目标之间相互访问 appDelegate 实例的正确方法吗?

Should I use some kind of Protocole & Generic Typing?我应该使用某种协议和通用类型吗?

Or should I simply build a ManagedObjectController for each target?或者我应该为每个目标简单地构建一个 ManagedObjectController 吗?

Thanks谢谢

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!但是在这种情况下, UIApplicationNSApplication已经支持了你需要的常用功能! 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 .一个值得考虑的替代方案是:与其声明两个类IosAppDelegateMacAppDelegate不如声明一个类AppDelegate ,然后将脏的#if代码从ManagedObjectsController类移到AppDelegate 中 Then, this AppDelegate could be used wherever you need a reference to the shared app delegate.然后,这个AppDelegate可以在任何需要引用共享应用程序委托的地方使用。 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.但是,如果您想尽快将您的产品推出市场,并且这个ManagedObjectsController是您需要共享应用程序委托的唯一地方,那么您的代码就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM