RealmMapper 3.0

RealmMapper 3.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Dec 2017
SwiftSwift Version 3.1
SPMSupports SPM

Maintained by DaoNV, Dai Ho V..



 
Depends on:
RealmSwift~> 3.0
ObjectMapper~> 2.2
 

  • By
  • Dao Nguyen

Realm + ObjectMapper

Requirements

  • iOS 8.0+
  • Xcode 8.3 (Swift 3.1)

Installation

Embedded frameworks require a minimum deployment target of iOS 8

Usage

Mapping

Rule:

  • Object has primaryKey must be StaticMappable (i)
  • Object has no primaryKey should be Mappable (ii)
import RealmSwift
import ObjectMapper
import RealmMapper

final class User: Object, StaticMappable {
    dynamic var id: String!
    dynamic var name: String?
    dynamic var address: Address?
    let dogs = List<Dog>()
    
    override class func primaryKey() -> String? {
        return "id"
    }
    
    func mapping(map: Map) {
        name <- map["name"]
        address <- map["address"]
        dogs <- map["dogs"]
    }
      
    static func objectForMapping(map: Map) -> BaseMappable? {
        do {
            let realm = try Realm()
            return realm.object(ofType: self, forMapping: map)
        } catch {
            return nil
        }
    }
}

// (ii)
final class Address: Object, Mappable {
    dynamic var street = ""
    dynamic var city = ""
    dynamic var country = ""

    dynamic var phone: Phone?

    let users = LinkingObjects(fromType: User.self, property: "address")

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        street <- map["street"]
        city <- map["city"]
        country <- map["country"]
        phone <- map["phone"]
    }
}

Import JSON to Realm

do {
  let realm = try Realm()
  try realm.write {
    realm.map(User.self, json: jsUser) // map JSON object
    realm.map(Shop.self, json: jsShops) // map JSON array
  }
} catch {
}

nil value will be bypass, if you want set nil please use NSNull() instead