我有一个项目,它使用 ObjectMapper 进行 JSON 序列化和反序列化,并使用 Realm 在本地缓存数据。我从 Rest API 获取数据并将它们正确保存到领域数据库中,我已经使用 RealmStudio 进行了检查。问题是当我从数据库中检索数据时,对象类型的属性返回 nil!这是我的课,foodFact 是 Object 类型,当从数据库中获取 FoodRecipe 数据时为 nil。有什么想法吗?
import RealmSwift
import ObjectMapper
typealias Syncable = Object & Mappable
class FoodFact: Syncable {
@objc dynamic var objectId :String = ""
@objc dynamic var calcium: String = ""
@objc dynamic var iron: String = ""
@objc dynamic var fiber: String = ""
@objc dynamic var fattyTransAcide: String = ""
override static func primaryKey() -> String? {
return "objectId"
}
required convenience init?(map: Map) { self.init() }
func mapping(map: Map) {
self.objectId <- map["objectId"]
self.calcium <- map["calcium"]
self.iron <- map["iron"]
self.fiber <- map["fiber"]
self.fattyTransAcide <- map["fattyTransAcide"]
}
}
class FoodRecipe: Syncable {
@objc dynamic var objectId :String = ""
@objc dynamic var title :String = ""
var ingredient = List<FoodRecipeIngredient>()
@objc dynamic var foodFact :FoodFact? //returns nil when retrieving data
override static func primaryKey() -> String? {
return "objectId"
}
required convenience init?(map: Map) { self.init() }
func mapping(map: Map) {
objectId <- map["objectId"]
title <- map["title"]
ingredient <- (map["ingredients"],ArrayTransform<FoodRecipeIngredient>())
foodFact <- map["foodFact"]
}
}
这是我用于保存和检索数据的代码:
import Foundation
import RealmSwift
protocol BaseDao {
associatedtype T: Object
func save(list:[T])
func save(object:T)
func get() -> [T]?
func delete(list:[T])
func deleteAll()
}
extension BaseDao {
func deleteAll(){
PersistenceManager().deleteDatabase()
}
}
class PersistenceManager {
let realm = try! Realm()
var notificationToken = NotificationToken()
func deleteObjects(objs:[Object]) {
do {
try realm.write({
realm.delete(objs)
})
} catch let error {
assertionFailure(error.localizedDescription)
}
}
func saveObjects(objs: [Object]) {
print("path for realm \(String(describing: realm.configuration.fileURL))")
do {
try realm.write({
realm.add(objs, update: true)
})
} catch let error {
assertionFailure(error.localizedDescription)
}
}
func saveObject(obj: Object) {
print("path for realm \(String(describing: realm.configuration.fileURL))")
do {
try realm.write({
realm.add(obj, update: true)
})
} catch let error {
assertionFailure(error.localizedDescription)
}
}
func getObjects(type: Object.Type) -> Results<Object>? {
return realm.objects(type)
}
func deleteDatabase() {
do {
try realm.write({
realm.deleteAll()
})
} catch let error {
assertionFailure(error.localizedDescription)
}
}
}
class FoodRecipeLocalPersistence :BaseDao {
typealias T = FoodRecipe
let persistenceManager :PersistenceManager
init(persistenceManager :PersistenceManager = PersistenceManager()) {
self.persistenceManager = persistenceManager
}
func save(list: [T]) {
self.persistenceManager.saveObjects(objs: list)
}
func save(object: T) {
self.persistenceManager.saveObject(obj: object)
}
func get() -> [T]? {
guard let data = persistenceManager.getObjects(type: T.self) else {
return nil
}
return Array(data) as? [T]
}
func delete(list: [T]) {
self.persistenceManager.deleteObjects(objs: list)
}
}
更新 1:经过进一步审查后,我意识到我可以检索 FoodRecipe 与 FoodRecipePersistence 中的所有属性,但在我的 ViewModel 中 FoodFact 为零!我在我的 ViewModel 中使用 RxSwift 下面是代码片段:
Observable.combineLatest(selectedCategory, currentCategory, resultSelector: { (selectedCategory, currentCategory) in
switch currentCategory {
case .Food:
let category = selectedCategory as? FoodRecipeCategory
return foodRecipeLocalPersistence.get()?.filter{ $0.categoryId == category?.objectId }.map{$0} ?? []
case .Sport:
let category = selectedCategory as? ExerciseInstructionCategory
return exerciseInstructionLocalPersistence.get()?.filter{ $0.categoryId == category?.objectId }.map{$0} ?? []
}
}).asObservable().bind(to: self.shownList).disposed(by: disposeBag)
更新 2:当我使用
po foodRecipe.foodFact
foodFact 打印在控制台上,包含所有数据和属性,但是当我将鼠标放在编辑器内的 foodRecipe.foodFact 上时,它显示为零!