I\'m using the Swift boilerplate code for Core Data in a fresh project. My .xcdatamodeld
file has a single entity defined (Task
) with a single attr
An update for @Ben Gottlieb answer under XCode 7.1 and Swift 2.0
@objc class ImageRecordMO: NSManagedObject{
Open your .xcdatamodled file.
Select your entity and click the data model inspector on the right panel.
Enter the class name, see the figure below
Select your module to be Current Product Module, see the figure below.
This is even frustrated if you tried all the above suggestions and non of them working for me!!
So this is what works for me.
1- Select your xcdatamodeld file
2- Make sure that all your entities has No Module in the "Data Model Inspector", if you see "Model: Current Product Module" ..clear it it so it looks like the attached image.
3- Delete your App to clear core data
4- If still not working, delete your entities and regenerate them.
I've run into this problem in the last few days and strangely the solution that worked for me was a variant of that suggested above.
I added the @objc declaration to the generated subclasses, but removed any namespace prefix in the class name in the object model (it had a default prefix of "PRODUCT_MODULE_NAME." after the subclasses were generated). That worked.
I guess only changing the class field in the .xcdatamodel doesn't work anymore because I still got the following exception: fatal error: use of unimplemented initializer 'init(entity:insertIntoManagedObjectContext:)' for class
So, I entered this code in my custom class:
init(entity: NSEntityDescription!,
insertIntoManagedObjectContext context: NSManagedObjectContext!) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
Suddenly, it worked! The NSManagedObject is now down-castable to my custom class. I can't really understand why this is the solution, but it works :)
You need to modify your Task.swift file. Adding @objc(Task) like below
import CoreData
@objc(Task)
class Task: NSManagedObject {
@NSManaged var name: String
}
I think this as a bug if your project does not contain any objective-c codes. However, you need to add that line until this fixed.
I learned it from here.
Youtube video at 11:45
Xcode 7 + Swift 2
Person.swift
@objc(Person)
class Person: NSManagedObject {
}
Data model
Then simply call
let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: self.managedObjectContext) as! Person