Author Topic: Xcode Tip: How to Reuse a Single Data Model from iOS, watchOS, and tvOS Projects  (Read 4623 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
When creating a universal app that runs on multiple platforms such as iOS, watchOS, and tvOS you should reuse as much of your app's code as possible, including Core Data.

However, there are some specific steps you need to take to access a single Data Model from multiple projects, to avoid the infamous error "Unable to load class named 'X' for entity 'X'. Class not found, using default NSManagedObject instead."

Here are the main steps:

1. Add the Data Model to the project that contains your Core Data code.

2. If you have separated each of your app's (iOS, watchOS, tvOS) user interface into a separate project (I recommend you do), you need to add a reference to the Data Model in each project's Compile Sources in the Project Editor.

3. In the Data Model, select each entity, go to the Data Model Inspector and make sure the Module setting is blank.

4. In each generated entity class file, add the @objc attribute. For example:

Code: [Select]
import Foundation
import CoreData

@objc(SettingsEntity)
public class SettingsEntity: NSManagedObject {
}

Now you can access the entities from any of your Xcode projects!

All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11
Check out our Robot Tic-Tac-Toe app: https://itunes.apple.com/us/app/robot-tic-tac-toe/id990638517?mt=8