jsonswiftcore-datacodablensvaluetransformer

Do all attributes with a custom type in core-data have to be a relationship?


This is a followup question from the comments in the following How to map nested complex JSON objects and save them to core data?.

Imagine that I already have this code for my app.

class Passenger{
    var name: String
    var number: String
    var image : UIImage
    // init method
}
class Trip {
    let tripNumber : Int
    let passenger : Passenger

    init(tripNumber: Int, passenger: Passenger) {
        self.tripNumber = tripNumber
        self.passenger = passenger
    }
}

Now I've decided to add persistence for my app. I just want to have a table of Trips. I want to show the passengers under trips, but don't need a table to query passengers directly. It's just a custom object/property of trip. Every time I access passenger it would be through Trips.

So is there a way that I can create a new subclass of NSManagedObject named 'TripEntity' and store my passengers — WITHOUT 1. creating another NSManagedObject subclass for 'Passenger' 2. Creating a relationship with an inverse relationship between Passenger and Trip? Simply put I just want it to be an attribute. Conceptually to me it's also just an attribute. It's not really a relationship...

Or is that once you're using Core-data then every custom type needs to be explicitly a subclass of NSManagedObject? Otherwise it won't get persisted. I'm guessing this also what object graph means. That your graph needs to be complete. Anything outside the graph is ignored...

I'm asking this because the JSON object that I actually want to store is gigantic and I'm trying to reduce the work needed to be done.


Solution

  • Any custom property needs to be something that can be represented as one of the Core Data property types. That includes obvious things like strings and numeric values. It also includes "binary", which is anything that can be transformed to/from NSData (Data in Swift).

    From your description, the best approach is probably to

    1. Adopt NSCoding for your Passenger class.
    2. Make the passenger property a Core Data "transformable" type. (as an aside, should this be an array of passengers? You have a single related passenger, but your question describes it as if there's more than one).
    3. After doing #2, set the "custom class" field for the passenger property to be the name of your class-- Passenger.

    If you do these two things, Core Data will automatically invoke the NSCoding methods to convert between your Passenger class and a binary blob that can be saved in Core Data.