ios - 如何在单独的 swift 文件中进行 Realm CRUD 操作?

标签 ios swift realm

我是 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'

enter image description here

我想我在 realm.objects 中插入 object.self 时犯了错误。它应该是 element.type,但我不知道像这张图片这样的元素类型是什么 enter image description here

如何从 Realm 加载数据?遗憾的是,我只是通过使用 realm.objects(object.self)

从 youtube 教程中了解到一点点

最佳答案

您正在通过对象执行选择工作,这是一个错误,因为它需要对象类型 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/

相关文章:

ios - UICollectionViewCell 中的 Realm 对象级通知

ios - SwiftUI 结合 Debounce TextField

ios - 如何使 UITableviewCell(自定义)高度取决于内容?

ios - 是在主线程中调用 AVAssetImageGenerator 完成处理程序吗?

ios - 更改对象的局部坐标(swift3)

swift - 如何强制包含计算属性?

ios - 捕获前置摄像头 - Phonegap?

ios - swift 中的 barTintColor

ios - Swift:无法打开枚举关联值

ios - RealmSwift - 如何将数据存储在列表中