Create entity programmatically and save in core data

0

Hello, I was wondering how I can save an entity in the core data programmatically.

I tried the following procedure:

Passing Parameter

MatchCoreData().createEntity(name: "Partidas123")

Func creating entity (I believe it's missing save in the core)

public func createEntity(name: String)
{

    // Create the entity
    var entities = Array<NSEntityDescription>();
    let model = NSManagedObjectModel()
    let entity = NSEntityDescription()


    if entities.count == 0
    {
        entity.name = name
        entity.managedObjectClassName = String(describing: Match.self)

        entities.append(entity)
        model.entities = [entity]

        saveContext()
    }


    for item in entities
    {

        if (item.name?.contains(name))!
        {
        }else
        {
            entity.name = name
            entity.managedObjectClassName = String(describing: Match.self)

            model.entities = [item]
            saveContext()

        }
    }
}
    
asked by anonymous 17.10.2017 / 18:41

1 answer

0

I usually do this:

func saveTransaction(name: String, value: Decimal) -> Transaction {
    let context = CoreDataManager.shared.persistentContainer.viewContext
    let tr = NSEntityDescription.insertNewObject(forEntityName: "Transaction", into: context)
    tr.setValue(name, forKey: "name")
    tr.setValue(value, forKey: "value")

    do {
        try context.save()
    } catch let saveErr {
        print("Failed to save transaction:", saveErr)
    }

    return tr as! Transaction
}

Where CoreDataManager is a singleton that contains my NSPersistentContainer .

    
22.03.2018 / 21:01