踊る犬.netブログ (旧)

ObjectMapper+RealmでTo-Many relationshipsを実装する方法

Person [1]-[0..*] Dog の関係を考える。

説明するよりコード見せたほうが早い:

import UIKit
import RealmSwift
import ObjectMapper

class Person: Object {
  dynamic var dogs = List<Dog>()
}

extension Person: Mappable {

  class func newInstance(map: Map) -> Mappable? {
    return Person()
  }

  func mapping(map: Map) {
    result <- (map["dogs"], ArrayTransform<Dog>())
  }

}

class Dog: Object {
  dynamic var name: String = ""
}

extension Dog: Mappable {

  class func newInstance(map: Map) -> Mappable? {
    return Dog()
  }

  func mapping(map: Map) {
    name <- map["name"]
  }

}

ArrayTransformこちらから拝借。作者に感謝!

// 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

class ArrayTransform<T:RealmSwift.Object where T:Mappable> : TransformType {
    typealias Object = List<T>
    typealias JSON = Array<AnyObject>

    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
    }

    func transformToJSON(value: List<T>?) -> Array<AnyObject>? {
        if (value?.count > 0)
        {
            var result = Array<T>()
            for entry in value! {
                result.append(entry)
            }
            return result
        }
        return nil
    }
}