我从服务器加载一个对象列表,并使用ObjectMapper将它们保存到Realm。每个对象都包含一个URL,用于定义加载对象图像的位置。我加载图像并将图像数据保存在领域对象中,这样我就不需要每次都重新加载它。但遗憾的是,如果我重新加载数据,图像数据就会丢失。
我使用主键,我的想法是当JSON时。我担心ObjectMapper不会更新Realm中的现有对象,但会覆盖它们。因此imagedata为nil,必须从服务器重新获取。我能做些什么来阻止这种情况吗?
这是我简化的ObjectMapping-File:
import Foundation
import ObjectMapper
import RealmSwift
class OverviewItem: PersistentObject {
override var hashValue : Int {
get {
return self.overviewID.hashValue
}
}
dynamic var overviewID: Int = 0
dynamic var titleDe: String = ""
dynamic var imageUrl: String = ""
dynamic var imageData: NSData?
required convenience init?(_ map: Map) {
self.init()
}
//computed properties
dynamic var image: UIImage? {
get {
return self.imageData == nil ? nil : UIImage(data: self.imageData!)
}
set(newImage){
if let newImage = newImage, data = UIImagePNGRepresentation(newImage){
self.imageData = data
}
else{
self.imageData = nil
}
}
}
//image is a computed property and should be ignored by realm
override class func ignoredProperties() -> [String] {
return ["image"]
}
override func mapping(map: Map) {
overviewID <- map["infoid"]
titleDe <- map["titleDe"]
imageUrl <- map["imageurl"]
}
override class func primaryKey() -> String {
return "overviewID"
}
}
在这里我如何获取图像并更新对象:
func fetchImage(item: OverviewItem, successHandler: UIImage? ->(), errorHandler: (ErrorType?) -> ()){
AlamofireManager.Configured
.request(.GET, item.imageUrl)
.responseData({ (response: Response<NSData, NSError>) in
if let error = response.result.error{
logger.error("Error: \(error.localizedDescription)")
errorHandler(error)
return
}
if let imageData = response.result.value{
successHandler(UIImage(data: imageData))
let overviewID = item.overviewID
let queue = NSOperationQueue()
let blockOperation = NSBlockOperation {
let writeRealm = try! Realm()
do{
if let itemForUpdate = writeRealm.objects(OverviewItem).filter("overviewID = \(overviewID)").first{
try writeRealm.write{
itemForUpdate.imageData = imageData
writeRealm.add(itemForUpdate, update: true)
}
}
}
catch let err as NSError {
logger.error("Error with realm: " + err.localizedDescription)
}
}
queue.addOperation(blockOperation)
}
})
}