ios - NSManagedObjectContextDidSaveNotification useless? -
i using core data while background contex, , wondering why advise use nsmanagedobjectcontextdidsavenotification
merging background main context. created test-project 1 nspersistentstorecoordinator
, main context , background context. here code fragment initalisation:
- (nsmanagedobjectcontext *)managedobjectcontext { if (_managedobjectcontext != nil) { return _managedobjectcontext; } nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator]; if (coordinator != nil) { _managedobjectcontext = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsmainqueueconcurrencytype]; [_managedobjectcontext setpersistentstorecoordinator:coordinator]; } return _managedobjectcontext; } - (nsmanagedobjectcontext *)backgroundcontext { if (_backgroundcontext != nil) { return _backgroundcontext; } _backgroundcontext = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsprivatequeueconcurrencytype]; _backgroundcontext.persistentstorecoordinator = self.persistentstorecoordinator; return _backgroundcontext; }
until now, have listened save notification this:
[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(mergechanges:) name:nsmanagedobjectcontextdidsavenotification object:self.backgroundcontext];
but realised, doesn't matter if merge notification. can edit , save either context, , other 1 get's merged after seconds itself.
so. question, why need nsmanagedobjectcontextdidsavenotification
?
your contexts not related. both root contexts attached same persistent store coordinator.
a change persistent store automatically pushed root contexts associated (which why don't need handle nsmanagedobjectcontextdidsavenotification
notification.)
nsmanagedobjectcontextdidsavenotification
useful when dealing more complex context ancestry, since mid-level context not automatically notify of children when changed.
as example, check out architecture diagram cadmium (https://github.com/jmfieldman/cadmium). when background child context saves writer context, main context must handle nsmanagedobjectcontextdidsavenotification
on main thread incorporate updates.