Question

I thinking about how to sync core data to backend. What do you think it is possible to use categories to extend the i.e. insertNewObjectForEntityForName method, and in the added logic I could call the appropriate restful webservice to insert record on backend too?!

Was it helpful?

Solution

No, because

  • You can't extend existing methods in categories. You could subclass NSEntityDescription to extend the method, but it's not a good idea for this purpose because...
  • This is the wrong time to sync. This method creates a new instance but doesn't assign any attribute values. So, you have no data to sync except "a new object exists". Even if you're sure to make your network calls on a separate thread, you have no useful information to send.
  • This won't help you with syncing changes from the server into your app.
  • In many cases apps create new objects but then don't save them (e.g. if the user taps a "cancel" button). If you use this method, you've already sent a new object to the server that you don't want.

There are numerous frameworks and paid services that help with syncing Core Data in one way or another. Which would be good (if any) really depends on what you're trying to accomplish-- syncing data to a user account on your server, or syncing data between multiple iOS devices, or whatever.

If you write your own sync code (which will be hard to get right) a common approach is to observe NSManagedObjectContextObjectsDidChangeNotification or NSManagedObjectContextDidSaveNotification or NSManagedObjectContextWillSaveNotification, or some combination of more than one of those. These will notify you whenever you have outgoing changes to send to your server. Import changes from the server using whatever API your server provides.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top