Showing posts with label model by code. Show all posts
Showing posts with label model by code. Show all posts

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)