swift 使用ObjectMapper将数组转换为Realm的List类型

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 使用ObjectMapper将数组转换为Realm的List类型相关的知识,希望对你有一定的参考价值。

// Based on Swift 1.2, ObjectMapper 0.15, RealmSwift 0.94.1
// Author: Timo Wälisch <timo@waelisch.de>

import UIKit
import RealmSwift
import ObjectMapper
import SwiftyJSON

class ArrayTransform<T:RealmSwift.Object where T:Mappable> : TransformType {
    typealias Object = List<T>
    typealias JSON = Array<AnyObject>
    
    let mapper = Mapper<T>()
      
    func transformFromJSON(value: AnyObject?) -> List<T>? {
        var result = List<T>()
        if let tempArr = value as! Array<AnyObject>? {
            for entry in tempArr {
                let mapper = Mapper<T>()
                let model : T = mapper.map(entry)!
                result.append(model)
            }
        }
        return result
    }
    
    // transformToJson was replaced with a solution by @zendobk from https://gist.github.com/zendobk/80b16eb74524a1674871
    // to avoid confusing future visitors of this gist. Thanks to @marksbren for pointing this out (see comments of this gist)
    func transformToJSON(value: Object?) -> JSON? {
        var results = [AnyObject]()
        if let value = value {
            for obj in value {
                let json = mapper.toJSON(obj)
                results.append(json)
            }
        }
        return results
    }
}
// SampleModel.swift
// Author: Timo Wälisch <timo@waelisch.de>

import UIKit
import ObjectMapper
import RealmSwift
import SwiftyJSON

class SampleModel: Object, Mappable {
    
    // MARK: Realm - stored properties
    
    dynamic var title: String = ""
    var products = List<ProductModel>()

    // MARK: ObjectMapper
    
    class func newInstance(map: Map) -> Mappable? {
        return SampleModel()
    }
    
    /// Mapping between ObjectMapper (JSON) and the model properties
    func mapping(map: Map) {
        title                   <- map["title"]
        products                <- (map["products"], ArrayTransform<ProductModel>())
    }
}

以上是关于swift 使用ObjectMapper将数组转换为Realm的List类型的主要内容,如果未能解决你的问题,请参考以下文章

Swift:如何将带有 Alamofilre 或 SwiftyJSON 的 JSON 字符串转换为 ObjectMapper?

Swift 和 ObjectMapper:具有最小值的 NSDate

ObjectMapper toJSON() 快速

Alamofire 和 Objectmapper 将数组数据添加到 tableview

使用 ObjectMapper - 如何将 JSON 结果快速转换为 TableView

无法在 Swift 中导入 ObjectMapper