在 createOrUpdateInDefaultRealmWithObject 中将 ISO 8601 字符串转换为日期

Convert ISO 8601 strings to date in createOrUpdateInDefaultRealmWithObject

我有一个从 REST API 返回的 JSON 块,格式如下:

[
  { 
    id: 1,
    locations: [
      {
        arriveAt: "2015-03-14T16:05:16Z"
      },
      {
        arriveAt: null
    ]
  },
  ...
]

然后我的项目中有这样的代码:

let trips = json as [NSDictionary]
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
for trip in trips {
  Trip.createOrUpdateInDefaultRealmWithObject(trip)
}
realm.commitWriteTransaction()

在我的位置 class 中,有一个变量 dynamic var arriveAt: NSDate?。我还使用 fromISO8601String 方法扩展了 NSDate,该方法初始化 NSDate,将 ISO 8601 字符串转换为日期。

有没有办法在 Realm 尝试创建 Location 对象时,它会自动 运行 从 JSON 到 NSDate.fromISO8601String 的字符串?

嗨,Dave,Realm 中还没有任何内置的东西可以为你做到这一点。您将需要使用 Realm-JSON 或 Mantle 等变压器