首页 文章

无法将数据保存到领域

提问于
浏览
0

我似乎无法在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存储数据(我可以使用领域浏览器进行验证) . 但是,一旦我重新启动应用程序,数据就不再存在于领域!有没有人建议为什么数据不会被保留?

EDIT 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"
 }

}

EDIT 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)
    }
  }
}

2 回答

  • 0

    我遇到了同样的问题 . 在我的领域课程中,我在存储的属性前面缺少@objc动态 . 所以添加如下 . 然后它对我有用 .

    @objc dynamic var address: Addres!
     @objc dynamic var checklist: Checklist!
    
  • 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
        }
    }
    

相关问题