0Pricing
SwiftUI Academy · Aula

Criando e Salvando Entidades

Insira registros e persista o contexto.

Criando e Salvando Entidades é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Adding New Data

Reading is half the story. To grow your app you also need to create new records and store them safely.

You Need the Context

Every new object is born inside a managed object context, so grab the context from the environment first.

@Environment(\.managedObjectContext) var context

Making an Instance

Create an entity by initialising it with the context, which registers the new object for tracking.

let task = Task(context: context)

Setting Attributes

Assign values to the object's attributes just like setting properties on any Swift object.

task.title = "Buy milk"
task.isDone = false

Nothing Is Saved Yet

At this point the record only lives in memory. It becomes permanent when you save the context.

Calling save()

Persist all pending changes at once with a single save call, wrapped in a do-catch for safety.

do {
    try context.save()
} catch {
    print("Save failed: \(error)")
}

Saving Is Transactional

One save writes every pending insert, edit, and delete together, so your store never lands half-updated.

Updating Existing Records

To edit, change the object's attributes and call save again. Core Data tracks what is dirty for you.

Deleting a Record

Remove an object with delete on the context, then save to make the removal stick.

context.delete(task)
try? context.save()

Why Catch Errors

Saving can fail, for example if a required value is missing, so handling the error keeps your app from crashing.

Save After Each Action

A common habit is to save right after the user adds, edits, or deletes, so work is never lost on a sudden close.

Quick Check

You created and stored a record. One quick question about the flow.

Recap

You learned to create an entity with the context, set its attributes, and call save to insert, update, or delete records. ✨

Perguntas Frequentes

A aula “Criando e Salvando Entidades” é grátis?

Sim — o texto completo de “Criando e Salvando Entidades” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.

O que vou aprender em “Criando e Salvando Entidades”?

Insira registros e persista o contexto. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar SwiftUI Academy?

Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.

Quanto tempo leva a aula “Criando e Salvando Entidades”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de SwiftUI Academy?

Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. A Pilha do Core Data
  2. Buscando com @FetchRequest
  3. Criando e Salvando Entidades
  4. Predicados e Descritores de Ordenação
← Voltar para SwiftUI Academy