using object mapper and realm as a database.
I'm getting a JSON from my server which contains person class I need to update some of properties then post it to server and update.
my person model class which I can not declare a list of object and this is the main problem
import RealmSwift
import ObjectMapper
import Realm
class person:Object, Mappable{
dynamic var firstNameFa:String=""
dynamic var lastLoginDate:String=""
dynamic var lastNameFa:String=""
dynamic var phone:String=""
dynamic var email:String?//=""
//var refercode:String?
dynamic var id:String=""
dynamic var identityId:String=""
//var password:String?
dynamic var userAccount:UserAccount?
dynamic var account:Account?
dynamic var code:String?
dynamic var address:Address? // tttt
var photo:Image?
dynamic var smartPhone="IPHONE"
var defaultAddressList:List<DefaultAddress>?
//dynamic var defaultAddressList = [DefaultAddress]() // this line is my problem
//dynamic var defaultAddressList:[DefaultAddress] = []
dynamic var serverToken=""
convenience required init?(map: Map) {
self.init()
}
func mapping(map: Map) {
firstNameFa <- map["firstNameFa"]
lastNameFa <- map["lastNameFa"]
identityId <- map["identityId"]
phone <- map["phone"]
email <- map["email"]
id <- map["id"]
userAccount <- map["userAccount"]
address <- map["address"]
defaultAddressList <- map["defaultAddressList"]
lastLoginDate <- map["lastLoginDate"]
account <- map["account"]
code <- map["code"]
photo <- map["photo"]
//defaultAddressList <- map["defaultAddressList"]
}
override class func primaryKey() -> String? {
return "id"
}
person is inside of data I'm retrieving it and putting in personJson
self.personJson = json["data"] as AnyObject
and finally casting into my model
self.psInfo = Mapper<person>().map(JSONObject: self.personJson)!
and my DefaultAddress is nill cause I have declared it as wrong way in model.all because realm
This was going long So I post my reply here.
Okay so to understand Transformation Class, you need to know that there are only few primitive types that we can use in JSON (like int, bool string, array etc). Now Realm List doesn't belong to any of this types, so in order to convert primitive types to required types like List<>
you will have to use TransformType from ObjectMapper.
I believe your JSOn has Array for address list which are by no means mappable to List<>
So, In order to convert the array to List<>
type, you need a TransformClass. If you see inside ObjectMapper Library you will see there are some already built in Transform Class e.g DateTransform()
that will transform Timestamp string to Swift Date
.
That is why you either have to write the transform class yourself or there is already a library built for that exactly, on GitHub -> ObjectMapper-Realm