If I use ObjectMapper with normal swift class, I am able to get JSON object created but when I use it with Realm class model, program crash. I tried to play around it ( check whether object exist, then using overriding primaryKey method but didn't help). I used class ListTransform from StackOverFlow and it seems to working fine. Xcode doesn't give any particular information on abend so that I can debug more. Other stackoverflow post doesn't help.
class UserResponse: Object, Mappable {
// MARK: Properties
//
var item = List<Item>()
dynamic var itemPurchaseDate = NSDate()
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
item <- (map["item"], ListTransform<Item>())
itemPurchaseDate <- (map["itemPurchaseDate"], ISO8601DateTransform())
}
}
class ListTransform<T:RealmSwift.Object where T:Mappable> : TransformType {
typealias Object = List<T>
typealias JSON = [AnyObject]
let mapper = Mapper<T>()
func transformFromJSON(value: AnyObject?) -> Object? {
let results = List<T>()
if let value = value as? [AnyObject] {
for json in value {
if let obj = mapper.map(json) {
results.append(obj)
}
}
}
return results
}
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
}
}
class Item: Object, Mappable {
// MARK: Properties
//
dynamic var itemName = ""
required convenience init?(_ map: Map) {
self.init()
}
// Mapping between ObjectMapper (JSON) and the model properties
//
func mapping(map: Map) {
itemName <- map["itemName"]
}
}
class RealmManager {
// returns a dictionary which represents give mappable object
//
func jsonFormat<N: Mappable>(object: N) -> [String: AnyObject] {
return Mapper().toJSON(object)
}
func uploadDataToBackend(someObject: UserResponse) {
let postData = jsonFormat(someObject)
print(postData)
}
}
-----------------------------------------
Program crash on following lines:
1. In Item class, program crash on line itemName <- map["itemName"]
2. If I comment above line , then I get crash on itemPurchaseDate <- (map["itemPurchaseDate "], ISO8601DateTransform())
Also note that, when Item does't have anything, first lines execute but when it does have data, it just crash. If you need any more information, please let me know