我是 iOS 开发和编程的初学者,我正在尝试制作一个包含名为 RealmService
的 Realm CRUD 操作的 swift 文件,因此我不必编写 do catch block 并尝试!到处都是 Realm ,就像我下面的代码
import Foundation
import RealmSwift
class RealmService {
var realm = try! Realm()
func save(_ object: Object) {
do {
try realm.write {
realm.add(object)
}
} catch {
print("Failed to save \(object) in realm: \(error.localizedDescription)")
}
}
func load(_ object: Object) -> Results<Object>? {
return realm.objects(object.self)
}
func update(_ object: Object, with dictionary: [String: Any?]) {
do {
try realm.write {
for (key, value) in dictionary {
object.setValue(value, forKey: key)
}
}
} catch {
print("Failed to update \(object) in realm: \(error.localizedDescription)")
}
}
func delete(_ object: Object) {
do {
try realm.write {
realm.delete(object)
}
} catch {
print("Failed to delete \(object) in realm: \(error.localizedDescription)")
}
}
}
但是在 load
方法中,我在 realm.objects(object.self)
行中得到一个错误,据说
Cannot convert value of type 'Object' to expected argument type 'Object.Type'
我想我在 realm.objects 中插入 object.self 时犯了错误。它应该是 element.type,但我不知道像这张图片这样的元素类型是什么
如何从 Realm 加载数据?遗憾的是,我只是通过使用 realm.objects(object.self)
最佳答案
您正在通过对象执行选择工作,这是一个错误,因为它需要对象类型 Element.Type
而不是对象本身
尝试使用这个
func load<T: Object>(ofType: T.Type) -> Results<T> {
return realm.objects(T.self)
}
调用这个函数
class MyObject: Object {
...
@objc dynamic var name = ""
...
}
.....
ream.objects(MyObject.self)
关于ios - 如何在单独的 swift 文件中进行 Realm CRUD 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264335/