Anders
Anders

Reputation: 2941

iOS NSManagedObjectContext - is it possible to get or send a notification when all changes is saved?

I use Core Data - and I have registered and is listening for NSManagedObjectContextDidSaveNotification:s I have a collection of data (from JSON), that I want to save, and after all objects is saved, I would like to get some kind of notification. It currently seems like this notification is sent after every object is saved. Is there some kind of built in solution for getting my desired notification? If not, how could/should I do it?

Upvotes: 0

Views: 238

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70976

There's no built-in notification that gets posted after you've saved a specific batch of objects. Core Data really has no idea how many objects are in your collection, so it has no way to know that you've reached the end of it.

You'll get NSManagedObjectContextDidSaveNotification every time you call save: on the managed object context. You could just wait to save until you've handled all of the objects, which would mean just one NSManagedObjectContextDidSaveNotification.

A better solution is to post your own notification when you know that you've finished the collection. Define a string constant called something like JSONUpdatesCompleteNotification, and post a notification with that name after your last save: call.

NSString *JSONUpdatesCompleteNotification = @"JSONUpdatesCompleteNotification";

Then later, when you know you're done,

[[NSNotificationCenter defaultCenter] postNotificationName:JSONUpdatesCompleteNotification object:self];

Make sure you observe this notification anywhere you need to know about it, and you're done.

Upvotes: 1

Related Questions