我似乎无法在Swift中将数据保存到领域!
在我的一个课程中,我有以下内容:
func getDeviceIdAndPersist(){
print("getDeviceIdAndPersist")
let realm = try! Realm()
let realmWallet = RealmWallet()
let realmResults = realm.objects(RealmWallet.self)
for results in realmResults {
guard results.deviceId != nil else {
realmWallet.deviceId = NSUUID().UUIDString
try! realm.write() {
realm.add(realmWallet, update: true)
}
return
}
}
}
它似乎没有保存数据!我的应用程序及其保存数据中的代码与此类似,但这不是!
此外,我在尝试保留数据时遇到问题,在启动应用程序后,使用realm存储数据(我可以使用领域浏览器进行验证)。但是,一旦我重新启动应用程序,数据就不再存在于领域!有没有人建议为什么数据不会被保留?
编辑1
这是我的领域课程
class RealmWallet: Object {
dynamic var publicKey = NSData()
dynamic var preferredAddress = ""
dynamic var id = 0
let walletAddresses = List<Addresses>()
dynamic var fee: NSNumber = 0.0
dynamic var deviceId: String? = nil
dynamic var tempPreTax: String? = nil
dynamic var portalToken: String? = nil
let walletHasBackup = RealmOptional<Bool>()
let alreadyAskedForBluetooth = RealmOptional<Bool>()
let insecureMailSent = RealmOptional<Bool>()
let cameraAccessGranted = RealmOptional<Bool>()
let idNowSuccess = RealmOptional<Bool>()
dynamic var marketInfos = NSData()
override class func primaryKey() -> String? {
return "id"
}
}
编辑2
NSUUID不是我无法保存的唯一数据,以下是使用Realm似乎无法保存的数据的另一个示例:
onboardingModal!.bluetoothPressed = {() -> Void in
print("after onboardingModal")
self.cbManager = CBCentralManager(delegate: self, queue: nil)
print("REALM")
let realm = try! Realm()
do {
try! realm.write {
print("IN WRITE")
self.realmWallet.alreadyAskedForBluetooth.value = true
realm.add(self.realmWallet, update: true)
}
}
}
答案 0 :(得分:0)
如果您的结果计数为0,则不会进入您的for循环。 试试这个。
func getDeviceIdAndPersist() {
let realm = try! Realm()
let realmResults = realm.objects(RealmWallet.self)
guard results.count > 0 else {
let realmWallet = RealmWallet()
realmWallet.deviceId = NSUUID().UUIDString
try! realm.write() {
realm.add(realmWallet, update: true)
}
return
}
}
答案 1 :(得分:0)
我遇到了同样的问题。在我的领域类中,我在存储的属性前面缺少@objc动态。因此,如下所示添加了它。然后它对我有用。
@objc dynamic var address: Addres!
@objc dynamic var checklist: Checklist!