gpt4 book ai didi

swift - 如何将 Realm 通知抽象为带有闭包的通用结构?

转载 作者:行者123 更新时间:2023-11-30 11:16:24 25 4
gpt4 key购买 nike

我的 View 模型当前包含以下代码:

private let project = RLMProject()
var projectToken: NotificationToken? = nil

projectToken = project.getDatabase()?.objects(RLMProject.self).observe { changes in ...

支持:

final class RLMProject: Object, Decodable, DatabaseLayer { ... 
typealias T = RLMProject
}

protocol DatabaseLayer {
associatedtype T: Object

func getDatabase() -> Realm?
}

extension DatabaseLayer {
func getDatabase() -> Realm? {
do {
return try Realm(fileURL: userRealmFile)
} catch let error {
DDLogError("Database error: \(error)")
return nil
}
}
...

我想做getDatabase()函数 private 但在封装通知闭包时遇到了麻烦, View 模型仍然可以为任何 <T: Object> 设置它,无需了解 Realm 的任何内部结构。

来自此的一些内容:

projectToken = project.getDatabase()?.objects(RLMProject.self).observe { [unowned self] ...

对此:

projectToken = project.setupNotificationToken { changes in ...

最佳答案

看来我已经成功了。

// Setup to observe Realm `CollectionChange` notifications
func setupNotificationToken(for observer: AnyObject, _ block: @escaping () -> Void) -> NotificationToken? {
if let database = self.getDatabase() {
return database.objects(T.self).observe { [weak observer] (changes: RealmCollectionChange) in
if observer != nil {
DDLogDebug("NotificationToken triggered on: \(observer!) for object: \(T.self)")
}
block()
}
} else {
return nil
}
}

示例:

projectToken = project.setupNotificationToken(for: self) { [unowned self] in
self.updateVC()
}

关于swift - 如何将 Realm 通知抽象为带有闭包的通用结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com