エンティティを作成して保存する
レコードを挿入し、コンテキストを永続化します。
「エンティティを作成して保存する」はCoddyKit上の無料SwiftUI Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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 contextMaking 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 = falseNothing 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. ✨
よくある質問
「エンティティを作成して保存する」レッスンは無料ですか?
はい。「エンティティを作成して保存する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、SwiftUI Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 SwiftUI Academyコースには全4レッスンが含まれています。
「エンティティを作成して保存する」で何を学びますか?
レコードを挿入し、コンテキストを永続化します。 ブラウザで直接実行するハンズオンコードでSwiftUI Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
SwiftUI Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSwiftUI Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「エンティティを作成して保存する」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSwiftUI Academyレッスンでコードを書いて実行できますか?
はい。すべてのSwiftUI Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Core Dataスタック
- @FetchRequestで取得する
- エンティティを作成して保存する
- 述語とソート記述子