質問編集履歴
1
追記
test
CHANGED
File without changes
|
test
CHANGED
@@ -67,3 +67,109 @@
|
|
67
67
|
|
68
68
|
|
69
69
|
参考:https://teratail.com/questions/48049
|
70
|
+
|
71
|
+
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
【追記】
|
76
|
+
|
77
|
+
下記の形で一応自己解決は出来たのですがこれは正しいやり方なのでしょうか・・・?
|
78
|
+
|
79
|
+
```ViewController
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
...省略...
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
@IBAction func saveButton(_ sender: UIButton) {
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
let realm = try! Realm()
|
92
|
+
|
93
|
+
|
94
|
+
|
95
|
+
// データベースの値を取得
|
96
|
+
|
97
|
+
let objs = realm.objects(Obj.self)
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
let obj = Obj()
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
// 値をセット
|
106
|
+
|
107
|
+
obj.name = textField.text
|
108
|
+
|
109
|
+
obj.target = Profiletextfield.text
|
110
|
+
|
111
|
+
|
112
|
+
|
113
|
+
// labelに表示
|
114
|
+
|
115
|
+
name.text = obj.name
|
116
|
+
|
117
|
+
Profile.text = obj.target
|
118
|
+
|
119
|
+
|
120
|
+
|
121
|
+
textField.text = ""
|
122
|
+
|
123
|
+
Profiletextfield.text = ""
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
// 上書き
|
128
|
+
|
129
|
+
DispatchQueue.main.async {
|
130
|
+
|
131
|
+
autoreleasepool {
|
132
|
+
|
133
|
+
|
134
|
+
|
135
|
+
let realm = try! Realm()
|
136
|
+
|
137
|
+
|
138
|
+
|
139
|
+
// DBにデータがない場合は書き込む
|
140
|
+
|
141
|
+
if(objs.count == 0){
|
142
|
+
|
143
|
+
try! realm.write() {
|
144
|
+
|
145
|
+
realm.add(obj)
|
146
|
+
|
147
|
+
}
|
148
|
+
|
149
|
+
} else{
|
150
|
+
|
151
|
+
// データベースに何か値がある場合はid=0を上書きする
|
152
|
+
|
153
|
+
let UserData = realm.objects(Obj.self).filter ("id == 0").first
|
154
|
+
|
155
|
+
|
156
|
+
|
157
|
+
try! realm.write {
|
158
|
+
|
159
|
+
UserData!.name = self.name.text
|
160
|
+
|
161
|
+
UserData!.target = self.Profile.text
|
162
|
+
|
163
|
+
}
|
164
|
+
|
165
|
+
}
|
166
|
+
|
167
|
+
}
|
168
|
+
|
169
|
+
}
|
170
|
+
|
171
|
+
|
172
|
+
|
173
|
+
}
|
174
|
+
|
175
|
+
```
|