0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Coredataで指定のオブジェクトの配列を一括削除する方法

Last updated at Posted at 2023-05-19

宣伝

アプリ作っているので入れてみてください!!
よろしくお願いいたします!!

本題

SwiftのCoredataをオンにして作った初期プロジェクトにある .onDelete(perform: deleteItems)
ですが、(以下です。)

func deleteItems(offsets: IndexSet) {
    withAnimation {
        offsets.map { archives[$0] }.forEach(viewContext.delete)

        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}

選択して削除ではなく、すべて削除したい場合があると思います。
すべてのアーカイブを削除するコードに変更するには、以下のように修正します。

func deleteAllArchives() {
    withAnimation {
        archives.forEach(viewContext.delete)

        do {
            try viewContext.save()
        } catch {
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
    }
}


ここではarchivesにcoredataのオブジェクトが入っているものとします。
この修正後の関数 deleteAllArchives() は、archives 配列内のすべてのアーカイブを削除します。変更が行われた後は、viewContext を保存して変更を反映させます。エラーが発生した場合は、エラーメッセージを表示します。

注意としてはデフォルトの何も検索条件をかけない状態で、このコードを実行すると、データベースの中身がすべて削除されてしまうので、気をつけてください。

作ったアプリ。

では。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?