SwiftUI Academy · 课时

创建与保存实体

插入记录并持久化上下文。

第 3 / 4 课13 个步骤

创建与保存实体 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SwiftUI Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SwiftUI Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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. ✨

免费开始

用 AI 导师学习 Swift — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
30
课程
120

常见问题解答

「创建与保存实体」课时是免费的吗?

是的 — 「创建与保存实体」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。

「创建与保存实体」这节课中我会学到什么?

插入记录并持久化上下文。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 SwiftUI Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「创建与保存实体」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 SwiftUI Academy 课中编写并运行代码吗?

能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Core Data 栈
  2. 使用 @FetchRequest 获取数据
  3. 创建与保存实体
  4. 谓词与排序描述符
← 返回 SwiftUI Academy