Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Sharing Core Data Model in App Group (w/ extension)

I'm trying to use the same core data model in my app as well as an extension, but am unsure how to share the core data model between the 2. The class for the core data model uses a namespace with the classname, so when I try and fetch the objects in the extension I get the unable to load class named "" error.

CoreData: warning: Unable to load class named 'Dali.Alarm' for entity 'Alarm'. Class not found, using default NSManagedObject instead.

Is there anyway to not use a namespace in the classname, or is there a way to make the extension inherit the namespace of the main project?

Core Data Entity

like image 474
Stephen Donnell Avatar asked Oct 18 '14 18:10

Stephen Donnell


People also ask

What is Coredata in Swift iOS?

Core Data is a graphical and persistence framework, which is used in Apple devices with operating systems macOS and iOS. Core Data was first introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0.

What is Persistentcontainer in Swift?

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).

What is app extension in Swift?

App extensions let you extend custom functionality and content beyond your app and make it available to users while they're interacting with other apps or the system.


1 Answers

I was stuck on this earlier. Seems like a real issue, and it wouldn't hurt to file it as a feature request/bug with Apple.

In the meantime, you can get around it with two steps. First, tag your NSManagedObject subclasses with @objc(ClassName). Simply insert it above the class declaration:

@objc(ClassName)
class ClassName: NSManagedObjectSubclass {
    @NSManaged var name : String
}

Second, go back to the managed object model, and remove the namespace from the "class" name field in the inspector for the Entity you're working with.

This worked for me today, after reading this: I can't use my core data model in two targets in a Swift project

like image 99
Steven Hovater Avatar answered Sep 28 '22 08:09

Steven Hovater