回答編集履歴

1

Todoクラスの定義でテスト

2020/05/03 03:07

投稿

ch3cooh
ch3cooh

スコア287

test CHANGED
@@ -39,3 +39,61 @@
39
39
 
40
40
 
41
41
  Realmの質問はどのようなオブジェクトを定義して扱っているのかがわからないと回答が難しいケースが多々ありますので、質問に `todo`クラスの定義も合わせて書いていただくとスムーズに回答がつくかと思います。
42
+
43
+
44
+
45
+ ### 追記1
46
+
47
+
48
+
49
+ todoクラスの定義をありがとうございます。早速試してみました。
50
+
51
+
52
+
53
+ ```
54
+
55
+ let realm = try! Realm()
56
+
57
+
58
+
59
+ try! realm.write {
60
+
61
+ let item = todo()
62
+
63
+ item.id = "393"
64
+
65
+ realm.add(item)
66
+
67
+ }
68
+
69
+
70
+
71
+ // 変数を使ってtodoを取得する
72
+
73
+ let id = "393"
74
+
75
+ let todoItem1 = realm.objects(todo.self).filter("id == '(id)'").first
76
+
77
+
78
+
79
+ // todoのidを文字列で指定する
80
+
81
+ let todoItem2 = realm.objects(todo.self).filter("id == '393'").first
82
+
83
+
84
+
85
+ // ソートしてからfilterを使う
86
+
87
+ let sortProperties = [
88
+
89
+ SortDescriptor(keyPath: "id", ascending: true)
90
+
91
+ ]
92
+
93
+ let todoItem3 = realm.objects(todo.self).sorted(by: sortProperties).filter("id == '393'").first
94
+
95
+ ```
96
+
97
+
98
+
99
+ いずれのケースでも問題なく Realmからオブジェクトの取得ができました。