ios - CoreData: removal of 'didSave' notification immediately after save: call. Too soon? -
-(void)somebackgroundtask { nsmanagedobjectcontext *context = [[nsmanagedobjectcontext alloc] initwithconcurrencytype:nsconfinementconcurrencytype]; [context setpersistentstorecoordinator:[self coordinator]]; // ... nsnotificationcenter *notificationcenter = [nsnotificationcenter defaultcenter]; [notificationcenter addobserver:self selector:@selector(handlesavenotification:) name:nsmanagedobjectcontextdidsavenotification object:context]; [context save:&error]; // safe? [notificationcenter removeobserver:self name:nsmanagedobjectcontextdidsavenotification object:context]; // ... } // meanwhile on main thread... -(void)handlesavenotification:(nsnotification *)notification { [[self context] mergechangesfromcontextdidsavenotification:notification]; }
is safe remove observer after call save:
?
as long you've received notification want, it's not soon. there other problems code.
it doesn't make sense add observer, trigger notification, , remove observer. might call handlesavenotification
method directly instead of bothering notifications. have same effect less work.
the reason notifications delivered synchronously on thread posted on. if somebackgroundtask
running on background thread or queue, handlesavenotification
run in background. using notifications doesn't make cross threads. merge on main thread, have few options, including:
- register notification using
addobserverforname:object:queue:usingblock:
. method can tell notification center queue use. make sure save reference object method returns-- you'll need later remove observer. - call merge method directly, in method use
dispatch_async
orperformselectoronmainthread:withobject:waituntildone:
move merge on main thread.
Comments
Post a Comment