2
votes

I'm having an issue using relationships in Core Data. I created my data model including the following entities: User, Conversation, Message, Participant - each containing a one-to-many relationship with the entity following it. I generated the classes for each entity using Editor -> Create NSManagedObject Subclass, and it correctly created the .Swift files for each class. The project builds, but when attempting to create and save a new user I get the following error:

2014-12-01 12:31:28.450 Messenger[2627:151403] CoreData: warning: Unable to load class named 'Messenger.User' for entity 'User'.  Class not found, using default NSManagedObject instead.

I made sure that my entity classes were prefixed with the project/module name (Messenger.User).

I also added "@ObjC(User)" directly above the User class, and added "-ObjC" to "Other Linker Flags" for the project, as suggested by people in various other posts. These are all the fixes that I could find, but I still get the same error. Here's what my User class looks like, for reference:

import Foundation
import CoreData
@objc(User)
class User: NSManagedObject {

    @NSManaged var api : API
    @NSManaged var username: String
    @NSManaged var userID: String
    @NSManaged var passcode: String
    @NSManaged var conversations: NSSet

    func findConversations(sourceView: MessengerViewController) {
        api.findConversations(sourceView)
    }
    func addConversation(newConversation: Conversation) {
        self.addConversationObject(newConversation)
    }
}
extension User {
    func addConversationObject(value: Conversation) {
        var items = self.mutableSetValueForKey("conversations");
        items.addObject(value)
    }
    func removeConversationObject(value: Conversation) {
        var items = self.mutableSetValueForKey("conversations");
        items.removeObject(value)
    }
}

Does anybody have an idea what else I did wrong? I've tried every fix I could come across, but nothing has seemed to work so far.

EDIT: The warning occurs when trying to create a new User object, at the third line below:

let userContext : NSManagedObjectContext = self.appDel.managedObjectContext!
let userEntity : NSEntityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: userContext)!
var newUser = User(entity: userEntity, insertIntoManagedObjectContext: userContext)
1

1 Answers

0
votes

Referring to my own answer, maybe you should also make sure you cast any fetch result to the appropriate class. E.g.

let result = context.executeFetchRequest(request, error:nil) as [User]

In response to your code update, you should perhaps try to insert new instances as follows.

var user = NSEntityDescription.insertNewObjectForEntityForName( "User", 
            inManagedObjectContext: context) as User