4
4

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 3 years have passed since last update.

SwiftUIでRealmを使う

Last updated at Posted at 2021-05-31

数ヶ月前に書いた↓を整理したものです。

はじめに

RealmSwiftの導入方法や基本的な仕様についてはUIKit版と同じため割愛します。
基本的なSwiftUIの仕様も割愛します。

テーブル(モデル)

SwiftUIではテーブルクラスにObjectKeyIdentifiableプロトコルを追加する必要があります。

class Book :Object,ObjectKeyIdentifiable{
/*属性*/
}

注意

これから説明する@ObservedResults@ObservedRealmObjectで扱われるデータはSwiftUIの仕様に対応するために 凍っています。
つまりデータを変更したい時にいつも通り書き込みトランザクションを開いてもそのまま変更することができません。必ずListやObjectを解凍する必要があります。

let thawItem = item.thaw() //オプショナル型で返ります
list.thaw()?.move(fromOffsets: indexSet, toOffset: index)//RealmListで並び替えを行う場合

検索

@ObservedResults(Book.self,filter:NSPredicate(format: "title != 'L'"),sortDescriptor:SortDescriptor(keyPath: "start", ascending: false)) private var results

イニシャライザからでも指定できます。
検索条件やソートは省略できます。
@ObservedResultsのResultsは、そのままForEachに入れることができます。

(Realmの)List

@ObservedRealmObject var parent:Hondana
//---
ForEach(parent.books){
book in
/*ここにView*/
}

@ObservedRealmObjectを付けるとForEachでRealmのListをそのまま扱えるようになります。
(リスト要素は解凍されていないことに注意してください)

onDeleteやonMoveについて

.onDelete(perform: $results.remove)

このように$を付けることで削除したりListの場合は移動することができますが、自分で書き込みトランザクション(realm.write{})処理を行う場合は、必ず前述したように**thaw()**を使用して解凍してください。

追記

古いバージョンのRealmだとSwiftUIのプレビューが失敗したりします。最新のバージョンを利用してください。

4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?