Programmatically create Entity and save to core data

Asked

Viewed 39 times

0

Hi, I was wondering how do I save an Entity in core data programmatically.

I tried the following procedure:

Passing parameter

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

Func creating the Entity (I believe it is 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()

        }
    }
}

1 answer

0

I usually do like 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.