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)
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.
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.
NSEntityDescription provides a user dictionary for you to store any related, app-specific information.
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.
Make sure you set the class name of you entity in the object model. The format is YourAppModule.YourClassName
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With