Last active
March 17, 2024 13:10
-
-
Save Jerrot/fe233a94c5427a4ec29b to your computer and use it in GitHub Desktop.
Transform arrays with ObjectMapper to Realm's List type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on Swift 1.2, ObjectMapper 0.15, RealmSwift 0.94.1 | |
// Author: Timo Wälisch <[email protected]> | |
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SampleModel.swift | |
// Author: Timo Wälisch <[email protected]> | |
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>()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks
I 'm use not optional forced unwrapping
This is my solution for Swift 4.2 & Xcode 10.1