Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does insertNewObjectForEntityForName only return a NSManagedObject?

I'm trying to move some RubyMotion code to Swift. So far it works. What I do not understand is why the following result can't be casted to the Document class:

var newObject : NSManagedObject 
  NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext:context) 
  as NSManagedObject

The insertNewObjectForEntityForName call returns an object of type NSManagedObject. But why doesn't insertNewObjectForEntityForName returns an object of type Document as specified by entity.managedObjectClassName ?

My Entity looks like this:

func DocumentEntity () -> NSEntityDescription {

    var entity = NSEntityDescription()
    entity.name = "Document"
    entity.managedObjectClassName = "Document"

    var property = NSAttributeDescription()
    property.name = "title"
    property.attributeType = NSAttributeType.StringAttributeType
    property.optional = false

    entity.properties = [property]

    return entity
}

class Document : NSManagedObject {
    @NSManaged var title : String
}

model = NSManagedObjectModel()
model.entities = [DocumentEntity()]

var store = NSPersistentStoreCoordinator(managedObjectModel: model)
like image 284
rogergl Avatar asked Jun 08 '14 10:06

rogergl


People also ask

How does Core Data work?

Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.

How do I get NSManagedObject?

Still inside the Core Data editor, go to the Editor menu and choose Create NSManagedObject Subclass. Make sure your data model is selected then click Next. Make sure the Commit entity is checked then click Next again.

What is an NSEntityDescription?

NSEntityDescription provides a user dictionary for you to store any related, app-specific information.

How do I save an object in Core Data?

To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core Data.


1 Answers

Make sure you set the class name of you entity in the object model. The format is YourAppModule.YourClassName.

enter image description here

like image 54
hgwhittle Avatar answered Nov 15 '22 14:11

hgwhittle