jeudi 21 janvier 2016

Fix uneccessary copy of NSManagedObject

I'm sorry the title may mislead you, since I'm not so good at English. Let me describe my problem as below (You may skip to the TL;DR version at the bottom of this question).

  1. In Coredata, I design a Product entity. In app, I download products from a server. It return JSON string, I defragment it then save to CoreData.

  2. After sometimes has passed, I search a product from that server again, having some interaction with server. Now, I call the online product XProduct. This product may not exist in CoreData, and I also don't want to save it to CoreData since it may not belong to this system (it come from other warehouse, not my current warehouse).

  3. Assume this XProduct has the same properties as Product, but not belong to CoreData, the developer from before has designed another Object, the XProduct, and copy everything (the code) from Product. Wow. The another difference between these two is, XProduct has some method to interact with server, like: - (void)updateStock:(NSInteger)qty;

  4. Now, I want to upgrade the Product properties, I'll have to update the XProduct also. And I have to use these two separately, like:


id product = anArrayContainsProducts[indexPath.row];
if ([product isKindOfClass:[XProduct class]] {
    // Some stuff with the xproduct
}
else {
    // Probably the same display to the cell.
}

TL;DR

Basically, I want to create a scenario like this:

  1. Get data from server.
  2. Check existed in CoreData.
  3. 2 == true => add to array (also may update some data from server).
  4. 2 == false => create object (contains same structure as NSManagedObject from JSON dictionary => add to array.

The object created in step 4 will never exist in CoreData.

Questions

  1. How can I create an NSManagedObject without having it add to NSMangedObjectContext and make sure the app would run fine?
  2. If 1 is not encouragement, please suggest me a better approach to this. I really don't like to duplicate so many codes like that.

Aucun commentaire:

Enregistrer un commentaire