質問編集履歴
1
エラーに関わる範囲のコードを追記
test
CHANGED
File without changes
|
test
CHANGED
@@ -71,3 +71,125 @@
|
|
71
71
|
Swiftのバージョンは3.0で、Realmのバージョンは2.0.0です。
|
72
72
|
|
73
73
|
どなたかわかる方がいれば教えていただきたいです。よろしくお願いします。
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
///追記///
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
エラーに関わる範囲のコードを追記しました。
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
```Swift
|
88
|
+
|
89
|
+
// MARK: - IBAction
|
90
|
+
|
91
|
+
|
92
|
+
|
93
|
+
@IBAction func addNewUser(_ sender: AnyObject) {
|
94
|
+
|
95
|
+
self.showAddNewUserAlert()
|
96
|
+
|
97
|
+
}
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
// MARK: - alertController
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
func showAddNewUserAlert() {
|
106
|
+
|
107
|
+
let alert:UIAlertController = UIAlertController(title:"登録", message: "名前を入力してね", preferredStyle: UIAlertControllerStyle.alert)
|
108
|
+
|
109
|
+
okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in
|
110
|
+
|
111
|
+
let textField = alert.textFields![0]
|
112
|
+
|
113
|
+
|
114
|
+
|
115
|
+
if self.checkHasSameUserNameInDatabase(textField.text!) { //エラーが出るメソッド
|
116
|
+
|
117
|
+
let user = User()
|
118
|
+
|
119
|
+
user.name = textField.text!
|
120
|
+
|
121
|
+
UserManager.sharedManager.insertUser(user)
|
122
|
+
|
123
|
+
UserManager.sharedManager.users.append(user)
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
let indexPath = IndexPath(row: UserManager.sharedManager.users.count - 1, section: 0)
|
128
|
+
|
129
|
+
self.tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
|
130
|
+
|
131
|
+
} else {
|
132
|
+
|
133
|
+
self.showFailureAlert()
|
134
|
+
|
135
|
+
}
|
136
|
+
|
137
|
+
})
|
138
|
+
|
139
|
+
|
140
|
+
|
141
|
+
let cancelAction:UIAlertAction = UIAlertAction(title: "キャンセル",
|
142
|
+
|
143
|
+
style: UIAlertActionStyle.cancel, handler:{
|
144
|
+
|
145
|
+
(action:UIAlertAction!) -> Void in
|
146
|
+
|
147
|
+
})
|
148
|
+
|
149
|
+
okAction.isEnabled = false
|
150
|
+
|
151
|
+
alert.addAction(cancelAction)
|
152
|
+
|
153
|
+
alert.addAction(okAction)
|
154
|
+
|
155
|
+
|
156
|
+
|
157
|
+
alert.addTextField(configurationHandler: {(text:UITextField!) -> Void in
|
158
|
+
|
159
|
+
text.placeholder = "名前"
|
160
|
+
|
161
|
+
text.delegate = self
|
162
|
+
|
163
|
+
})
|
164
|
+
|
165
|
+
present(alert, animated: true, completion: nil)
|
166
|
+
|
167
|
+
}
|
168
|
+
|
169
|
+
|
170
|
+
|
171
|
+
func checkHasSameUserNameInDatabase(_ name: String!) -> Bool {
|
172
|
+
|
173
|
+
let realm = try! Realm()
|
174
|
+
|
175
|
+
let predicate = NSPredicate(format: "name = %@", name)
|
176
|
+
|
177
|
+
let users = realm.objects(User.self).filter(predicate) //ここでエラーが出る
|
178
|
+
|
179
|
+
|
180
|
+
|
181
|
+
if users.count == 0 {
|
182
|
+
|
183
|
+
return false
|
184
|
+
|
185
|
+
} else {
|
186
|
+
|
187
|
+
return true
|
188
|
+
|
189
|
+
}
|
190
|
+
|
191
|
+
}
|
192
|
+
|
193
|
+
|
194
|
+
|
195
|
+
```
|