CoreStore icon indicating copy to clipboard operation
CoreStore copied to clipboard

Is it possible to have multiple ImportableUniqueObjects for the same NSManageObject?

Open tkirby opened this issue 2 years ago • 1 comments

I have two web fetches that update the same object at different times.

Hotel <- HotelJSON Hotel <- HotelPriceJSON

Both JSONs use HotelId as the unique key. Is it possible to make those both unique objects? Prrotocol can only be declared on Hotel once. Is there a workaround?

tkirby avatar Feb 13 '23 03:02 tkirby

Sure, I do something like this a lot in my projects:

class Hotel: CoreStoreObject, ImportableUniqueObject {
  // ...
  enum ImportSource {
    case hotelJSON([String: Any])
    case hotelPriceJSON([String: Any])
  }
}

then in your import code:

try transaction.importUniqueObjects(
  Into<Hotel>(),
  sourceArray: jsonArray.map({ .hotelJSON($0) }) // or .hotelPriceJSON depending on the method
)

Then in your ImportableUniqueObject implementation:

public func update(
  from source: ImportSource,
  in transaction: BaseDataTransaction
) throws {
  switch source {
    case .hotelJSON(let json):
      // parse as how you expect
    case .hotelPriceJSON(let json):
      // parse as how you expect
  }    
}

JohnEstropia avatar Feb 14 '23 05:02 JohnEstropia