Monday, October 9, 2017

Swift Core Data Create Entity Programmatically

Core Data provides a new layer to work with database in ease. We can create models(Entities) graphically without writing a single line of code. However, if you want to try with code, here is a sample one to try.


First create model to store all entities

let model = NSManagedObjectModel()

Create an entity called Person
let personEntity = NSEntityDescription()
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"

personEntity.properties.append(nameAttribute)

Finally add "personEntity" to previous model
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)




2 comments:

  1. If you have any question regarding to this topic or any errors with my content, please give me feedbacks.

    ReplyDelete
  2. how can we write and fetch data into and from this programmatically created entity ?

    ReplyDelete