1

I have an Image : NSManagedObject that has two properties: NSString* localPath and NSString* remoteUrl.

When I save the object by calling save:&error on the managed object context, I want it to download the file and when the download fails, I want the save operation to fail too.

Because I have a deeply nested DB structure with multiple references to my Image Entity it would be complicated to find all my images to trigger the download manually.

Is this possible, and if so, how can I cancel the save or delete operation so that it fails? If it's bad practice to do this in the Model, where should I do this?

stefreak
  • 1,460
  • 12
  • 30

3 Answers3

2

It's probably possible to do what you describe but it would be an incredibly bad idea. Downloading images can take a long time. Saving changes in Core Data can already take a while. Since saving will affect every instance that needs an image, you'd be taking a potentially long operation and turning it into a ridiculously, insanely, excessively long operation. Saving wouldn't complete until every image download had finished, and that's an extremely unreasonable dependency.

You'd be much, much, much better off having image downloading and saving changes completely decoupled from each other. Download images separately. If an object's image is unavailable, use a placeholder of some kind.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
0

Instead of having save: start the download process, which by the way saves the entire managed object context not just a single object, I would start the download first. If the download succeeds, you can write the image to disk, update the localPath and save your changes, if it fails then you don't need to do a save at all.

Jonathan Arbogast
  • 9,620
  • 4
  • 35
  • 47
  • Thanks for your answer, that's possible of course. But I have a db structure with 10 entities and they're nested deeply so it would be complicated to find all the images to save them. In addition to that, I get the data from an API and RestKit instanciates my objects. So I would be happy if it would be possible differently :) But I will accept your answer if there is no other solution, of course.. – stefreak Oct 04 '13 at 16:24
0

I think that MVCS (Model View Controller Service / Model View Controller Store) might be of interest to you. You could move your logic to the Store layer. It would perform image download asynchronously and create NSManagedObject if download completed successfully.

You can find some information about it at: MVCS - Model View Controller Service and https://softwareengineering.stackexchange.com/questions/184396/mvcs-model-view-controller-store

Community
  • 1
  • 1
Arek Holko
  • 8,966
  • 4
  • 28
  • 46
  • OK, that's interesting, thanks. But I'm already using RestKit for retrieving my objects from a REST service... I'm not sure how that would fit into using RestKit? – stefreak Oct 04 '13 at 16:33