【问题标题】:RealmSwift: How to properly Adopt to RealmOptionalType protocol on UInt?RealmSwift:如何在 UInt 上正确采用 RealmOptionalType 协议?
【发布时间】:2020-07-29 21:50:14
【问题描述】:

我有一个对象,其来自服务器的属性之一需要类型为 UInt,一旦从服务器解析数据,我的项目使用 RealmSwift 在本地存储数据。

这是示例用例:

import RealmSwift
import Foundation 

class MediaServerInfo: Object {
private var _hostPort = RealmOptional<UInt>()

}

// MARK: - Adopting to RealmOptionalType

// Here I am trying to adopt the protocol so that the _hostPort above can use RealmOptional<UInt>()

extension UInt: RealmOptionalType {
  public static func className() -> String {
    return "UInt"
  }
}

但是,当我进入使用上述类的页面时,我会立即收到以下运行时错误:-

 Terminating app due to uncaught exception 'RLMException', reason: ''RealmOptional<UInt>' is not a valid RealmOptional type.'

对此有什么想法吗?

【问题讨论】:

    标签: ios swift realm realm-mobile-platform


    【解决方案1】:

    Realm 不支持 UInt 类型。 Realm Cheatsheet 显示支持的类型以及文档中的此内容

    RealmOptional 支持 Int、Float、Double、Bool 和所有大小的 Int 的版本(Int8、Int16、Int32、Int64)。

    一种技术是将 Int 值存储在 Realm 中作为后备 var,并利用非托管 var 作为前端。

    class MediaServerInfo: Object {
       private let _hostPort = RealmOptional<Int>()
    
       var hostPort: UInt {
          get {
             let myInt = _hostPort.value ?? 0
             let u = UInt(myInt)
             return u
          }
        
         set {
            let myInt = Int(newValue)
            _hostPort.value = myInt
         }
       }
    }
    

    并在创建时这样使用

    let info = MediaServerInfo()
    info.hostPort = UInt(42)
    

    或阅读

    let x = info.hostPort
    

    【讨论】:

    • 嗨,@Jay 谢谢。我最终采用了几乎类似的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多