objective c - Disposing of NSManagedObjectContexts in a Core Data management class -
so making framework hold code used manipulate core data database. have ended having issue this.
i have method returns new item
- (nsmanagedobject *)createitem; once have modified item call
- (void)save; this has able executed in multiple threads managed object return method has have nsmanagedobjectcontext consistent inside thread. solution solve create nsmutabledictionary hold references nsmanagedobjectcontexts using
[nsthread hash] as key. works great. problem cannot rid of contexts once threads have finished.
does have idea on how detect that?
here code managed object context method
// return managed object context framework - (nsmanagedobjectcontext *)managedobjectcontext { // thread hash value nsthread * currentthread = [nsthread currentthread]; nsnumber * hashvalue = [nsnumber numberwithunsignedinteger:[currentthread hash]]; // context thread hash nsmanagedobjectcontext * context = [self.managedobjectcontexts objectforkey:hashvalue]; // check context exists if (!context) { // create managed object context persistent store coordinator in main thread nspersistentstorecoordinator * coordinator = [self persistentstorecoordinator]; if (coordinator != nil) { context = [[nsmanagedobjectcontext alloc] init]; [context setpersistentstorecoordinator:coordinator]; } // add context available contexts [self.managedobjectcontexts setobject:context forkey:hashvalue]; } // return return context; }
look @ using threaddictionary available on each nsthread. in way can moc thread (or know if there isn't one) , cleanup handled you.
Comments
Post a Comment