teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

Todoクラスの定義でテスト

2020/05/03 03:07

投稿

ch3cooh
ch3cooh

スコア287

answer CHANGED
@@ -18,4 +18,33 @@
18
18
  let filterRealm = realm.objects(todo.self).sorted(by: sortProperties).filter("id == '393'")
19
19
  ```
20
20
 
21
- Realmの質問はどのようなオブジェクトを定義して扱っているのかがわからないと回答が難しいケースが多々ありますので、質問に `todo`クラスの定義も合わせて書いていただくとスムーズに回答がつくかと思います。
21
+ Realmの質問はどのようなオブジェクトを定義して扱っているのかがわからないと回答が難しいケースが多々ありますので、質問に `todo`クラスの定義も合わせて書いていただくとスムーズに回答がつくかと思います。
22
+
23
+ ### 追記1
24
+
25
+ todoクラスの定義をありがとうございます。早速試してみました。
26
+
27
+ ```
28
+ let realm = try! Realm()
29
+
30
+ try! realm.write {
31
+ let item = todo()
32
+ item.id = "393"
33
+ realm.add(item)
34
+ }
35
+
36
+ // 変数を使ってtodoを取得する
37
+ let id = "393"
38
+ let todoItem1 = realm.objects(todo.self).filter("id == '(id)'").first
39
+
40
+ // todoのidを文字列で指定する
41
+ let todoItem2 = realm.objects(todo.self).filter("id == '393'").first
42
+
43
+ // ソートしてからfilterを使う
44
+ let sortProperties = [
45
+ SortDescriptor(keyPath: "id", ascending: true)
46
+ ]
47
+ let todoItem3 = realm.objects(todo.self).sorted(by: sortProperties).filter("id == '393'").first
48
+ ```
49
+
50
+ いずれのケースでも問題なく Realmからオブジェクトの取得ができました。