7

Let start from background of my problem.

I have a Person class which is used to parse JSON response

class Person: NSObject, Mappable {

        var ID : String?
        var firstName : String?
        var lastName : String?

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

            }

            func mapping(map: Map) {
                patientsCount <- map["patientsCount"]
                status <- map["status"]
                message <- map["Message"]
                patientSearchArray <- map["patientsList_JSON"]
            }
    }

While on the other I have another class names PersonMO which is used to save record in CoreData

        @objc(Event)
        class PersonMO: NSManagedObject {

        @NSManaged var ID : String?
        @NSManaged var firstName : String?
        @NSManaged var lastName : String?

    }

Now comes to main point. The problem I am facing is that I have to create two different classes for one purpose. Just like When JSON comes form Server Side then I have to parse it into Person class and then I want to save that Person into Core Data for that I have to convert Person class object to PersonMO class object. Which seems like a bad practice. Is there any way to use just one Class Person will be used to parse JSON and at the same time I want to use that Person class to store data in Core Data.

Usman Javed
  • 2,437
  • 1
  • 17
  • 26
  • It doesn't look like ObjectMappper supports this. But ObjectMappper is open source, so you could modify it and send a pull request to incorporate your change. – Tom Harrington May 17 '17 at 14:58
  • Did you ever find a solution to this if so please share as I am facing the same issue. – rmp Oct 18 '17 at 20:10

1 Answers1

0

A single Person class like this should be enough, would serve both cases.

class Person: NSManagedObject, Mappable { 

@NSManaged var ID : String?
@NSManaged var firstName : String?
@NSManaged var lastName : String?

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

}

func mapping(map: Map) {
    patientsCount <- map["patientsCount"]
    status <- map["status"]
    message <- map["Message"]
    patientSearchArray <- map["patientsList_JSON"]
}
}

NSManagedObject is subclass of NSObject so it can be used just like your Person class with Mappable. @NSManaged is a indication that its managed by CoreData, still it can be used like normal variables.

Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
  • 1
    I have already tried this approach. When you set NSManagedObject as a Parent class you have to implement NSManagedObject's init methods then init?(map: Map) method does not call. So also mapping(map: Map) will also not called. – Usman Javed May 17 '17 at 09:45
  • What library are you using for Mapping? wanted to know how init?(map: Map) is getting called – Anil Varghese May 17 '17 at 09:53
  • I am using ObjectMappper to parse JSON response. – Usman Javed May 17 '17 at 10:11