使用领域更新列表中的值时获得通知

时间:2018-09-29 05:42:13

标签: swift realm

我正在尝试使用Realm数据库在OS X中编写应用程序。我想在另一个对象内部的List值发生变化的地方触发通知

下面是班级

final class Profile: Object {
    @objc dynamic var gradient1 = ""
    @objc dynamic var gradient2 = ""
    @objc dynamic var fontColor = ""
    @objc dynamic var selectedFont = ""
    @objc dynamic var selectedTitleFont = ""
    @objc dynamic var fontFamily = ""
    @objc dynamic var name = ""
    @objc dynamic var shortbio = ""
    @objc dynamic var avatarSource = ""
    @objc dynamic var userid = ""
    @objc dynamic var email = ""
    var features = List<Features>()
    var socialLinkButtons = List<SocialLinkButtons>()

    @objc dynamic var appSelectedMetaData : AppMetaData? = nil

    override static func primaryKey() -> String?{
        return "userid"
    }

}

final class Features: Object {
    @objc dynamic var uuid = ""
    @objc dynamic var id = ""
    @objc dynamic var label = ""
    @objc dynamic var screen = ""
    @objc dynamic var active = false

    override static func primaryKey() -> String?{
        return "id"
    }

    convenience init(id: String, uuid: String, label: String, screen: String, active: Bool) {
        self.init()
        self.id = id
        self.uuid = uuid
        self.label = label
        self.screen = screen
        self.active = active
    }
}

我想在功能内的值更新时触发通知。

1 个答案:

答案 0 :(得分:1)

您可以使用Realm Collection Notifications实现目标。您只需要确保将返回的NotificationToken存储在一个变量中,该变量在您实际上不再需要接收通知之前不会被释放,并且在以下情况下您对令牌调用.invalidate()您不再希望收到通知。

func observeFeatureChanges(in profile:Profile) -> NotificationToken {
    let notificationToken = profile.features.observe { changes in
        switch changes {
        case .update(_, deletions: let deletionIndices, insertions: let insertionIndices, modifications: let modIndices):
            print("Objects deleted from indices: \(deletionIndices)")
            print("Objects inserted to indices: \(insertionIndices)")
            print("Objects modified at indices: \(modIndices)")
        case .error(let error):
            print(error)
        case .initial(let type):
            print(type)
        }
    }
    return notificationToken
}