First create model to store all entities
let model = NSManagedObjectModel()
let personEntity = NSEntityDescription()
Create an attribute call Name with type of String
personEntity.name = "Person"
personEntity.managedObjectClassName = "Person"
Create an attribute call Name with type of String
let nameAttribute = NSAttributeDescription()
nameAttribute.name = "name"
nameAttribute.attributeType = .stringAttributeType
nameAttribute.isOptional = true
Add "nameAttribute" to "personEntity"
Finally add "personEntity" to previous model
personEntity.properties.append(nameAttribute)
model.entities.append(personEntity)
Congratulation, you just create an entity programmatically.
Here is the full code.
let model = NSManagedObjectModel()
let personEntity = NSEntityDescription()
personEntity.name = "Person"
personEntity.managedObjectClassName = "Person"
let nameAttribute = NSAttributeDescription()
nameAttribute.name = "name"
nameAttribute.attributeType = .stringAttributeType
nameAttribute.isOptional = true
personEntity.properties.append(nameAttribute)
model.entities.append(personEntity)
If you have any question regarding to this topic or any errors with my content, please give me feedbacks.
ReplyDeletehow can we write and fetch data into and from this programmatically created entity ?
ReplyDelete