0
votes

I am encountering a weird error when using Core Data with Swift in Xcode 7.3.

I recently updated our codebase from Swift 1.0 to Swift 2.2 and am now getting an error when trying to access certain elements of an NSManagedObject extension.

I've set up the entity (called Member here) in the data model as shown below, with the class name and module matching what I've seen in other posts:

Screenshot of Inspector View of Member Entity

The class itself has the following top most declaration:

@objc(Member) class Member: NSManagedObject {

And I've tried both removing and adding the @objc part at the top as it's something I've seen people mention might cause issues.

I instantiate an instance of my NSManagedObjects through a convenicnece initializer in an extension of NSManagedObject as shown below:

convenience init(context: NSManagedObjectContext, className: String) {
    let entity = NSEntityDescription.entityForName(className, inManagedObjectContext: context)
    self.init(entity: entity!, insertIntoManagedObjectContext: context)
}

Finally the error occurs when I try to set certain properties on the Member object. I thought it might have to do with whether the properties were optional or not but switching those around didn't seem to have an effect.

The error I get is an EXEC_BAD_ACCESS error, but it seems to stem from the following thing that gets printed out when I instantiate the Member object:

MyAppName[23325:891360] CoreData: warning: Unable to load class named 
'MyAppName.Optional("Member")' for entity 'Member'.  Class not found, 
using default NSManagedObject instead.

Any insight would be appreciated as I am unsure of what else to try, as well as why it's adding ".Optional" to the start of the class name.

Thank you.

1
How are you fetching the class name? - Robert Gummesson
Print className and verify what's being passed to your init. - Phillip Mills

1 Answers

0
votes

Don't force unwrap the optional you get back from NSEntityDescription.entityForName. You should probably put a guard let on the entity and throw if the entity does not return.

As an aside, I doubt this convenience method buys you anything over just calling NSEntityDescription.insertNewObjectForEntityForName(_:inManagedObjectContext:). You are still dealing with a magic string and the context.