There are three main components:
- UI action and saving changes in CoreData li>
- Saving changes to the server
- UI update with server response
NSOperation + NSOperationQueue helps streamline network requests. The delegate protocol will help your user interface classes understand the state of network requests, for example:
@protocol NetworkOperationDelegate - (void)operation:(NSOperation *)op willSendRequest:(NSURLRequest *)request forChangedEntityWithId:(NSManagedObjectID *)entity; - (void)operation:(NSOperation *)op didSuccessfullySendRequest:(NSURLRequest *)request forChangedEntityWithId:(NSManagedObjectID *)entity; - (void)operation:(NSOperation *)op encounteredAnError:(NSError *)error afterSendingRequest:(NSURLRequest *)request forChangedEntityWithId:(NSManagedObjectID *)entity; @end
The format of the protocol, of course, will depend on your specific use case, but essentially what you create is the mechanism by which changes can be “pushed” to your server.
It follows that the UI loop to consider, in order to keep your code clean, would be nice to call save: and the changes would be automatically redirected to the server. You can use NSManagedObjectContextDidSave notifications for this.
- (void)managedObjectContextDidSave:(NSNotification *)saveNotification { NSArray *inserted = [[saveNotification userInfo] valueForKey:NSInsertedObjects]; for (NSManagedObject *obj in inserted) {
The estimated overhead for inserting network operations should be fairly low, however, if it creates a noticeable delay in the user interface, you can simply extract the object identifiers from the storage notifications and create operations in the background thread.
If your REST API supports batch processing, you can even send the entire array immediately, and then notify the user interface that synchronized several objects.
The only problem that I foresee, and for which there is no “real” solution, is that the user does not want to wait until their changes are redirected to the server in order to be able to make more changes. The only good paradigm I came across is that you allow the user to continue editing objects and editing their edits together, i.e. Do not click on each save notification.
ImHuntingWabbits Oct 17 2018-10-10T00: 00-10
source share