gpt4 book ai didi

swift - 对象已被删除或无效 Realm

转载 作者:行者123 更新时间:2023-11-28 06:30:58 26 4
gpt4 key购买 nike

我让这个类继承自 Object:

class Location: Object {
dynamic var id: String = ""
dynamic var name: String = ""

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

此类在我的管理器中用作实例,如下所示:

class LocationServiceAPI {

fileprivate var _location: Location?
var location: Location? {
get {
if _location == nil {
let realm = try! Realm()
_location = realm.objects(Location.self).first
}
return _location
}
set {
let realm = try! Realm()

if let newValue = newValue {
// delete previous locations
let locations = realm.objects(Location.self)
try! realm.write {
realm.delete(locations)
}

// store new location
try! realm.write {
realm.add(newValue, update: true)
_location = newValue
}
} else {
let locations = realm.objects(Location.self)
try! realm.write {
realm.delete(locations)
}
}
}
}
}

因此,每当我得到一个位置时,我都会删除旧位置(新位置和旧位置可能相同)并用新位置替换它,然后我使用 newValue 作为属性的新值 _location 但每当我尝试访问 location 时,它都会给我“对象已被删除或无效”。

我真的很困惑,因为 location 将保存从 setter 传递的值而不是 Realm !!

注意:如果我停止删除,那么它将正常工作。

最佳答案

The Object has been deleted or invalidated 如果对象已从 Realm 中删除,但您随后尝试访问代码挂起的该对象实例的存储属性,则会发生错误从删除之前开始。

您需要检查您的逻辑路径并确保您无法删除位置对象,并且随后不更新 _location 属性。在您提供的示例代码中没有提到删除对象,但是您的 if let newValue = newValue 代码行意味着 _location 实际上不会被清除如果您传入 nil

最后,可以通过调用 _location.invalidated 手动检查一个对象是否已从 Realm 中删除,所以如果这种情况经常发生,最好包括一些额外的检查在您的代码中也是如此。

关于swift - 对象已被删除或无效 Realm ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358566/

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