ios - Can NSManagedObject conform to NSCoding -


i need transfer single object across device. right converting nsmanagedobject dictionary , archiving , sending nsdata. upon receiving unarchiving it. transfer nsmanagedobject archiving , unarchiving instead of creating intermediate data object.

@interface test : nsmanagedobject<nscoding> @property (nonatomic, retain) nsstring * title; @end  @implementation test @dynamic title;  - (id)initwithcoder:(nscoder *)coder {     self = [super init];     if (self) {         self.title = [coder decodeobjectforkey:@"title"]; //<crash     }     return self; } - (void)encodewithcoder:(nscoder *)coder {     [coder encodeobject:self.title forkey:@"title"]; } @end   nsdata *archivedobjects = [nskeyedarchiver archiveddatawithrootobject:testobj]; nsdata *objectsdata = archivedobjects; if ([objectsdata length] > 0) {     nsarray *objects = [nskeyedunarchiver unarchiveobjectwithdata:objectsdata]; } 

the problem above code is. crashes @ self.title in initwithcoder saying unrecognized selector sent instance.

  • why title not being recognized selector.
  • should unarchive use nil managed object context somehow before creating object in initwithcoder?
  • do need override copywithzone?

this snippet below should trick. main difference call super initwithentity:insertintomanagedobjectcontext:

- (id)initwithcoder:(nscoder *)adecoder {    nsentitydescription *entity = [nsentitydescription entityforname:@"test" inmanagedobjectcontext:<yourcontext>];     self = [super initwithentity:entity insertintomanagedobjectcontext:nil];    nsarray * attributenamearray = [[nsarray alloc] initwitharray:self.entity.attributesbyname.allkeys];     (nsstring * attributename in attributenamearray) {         [self setvalue:[adecoder decodeobjectforkey:attributename] forkey:attributename];    }    return self; } 

above snippet handle attributes, no relationships. dealing relationships nsmanagedobjectid using nscoding horrible. if need bring relationships across consider introducing attribute match 2 (or many) entities when decoding.

how obtain <yourcontext>

(based on unavailable post sam soffes, code taken https://gist.github.com/soffes/317794#file-ssmanagedobject-m)

+ (nsmanagedobjectcontext *)maincontext {      appdelegate *appdelegate = [appdelegate sharedappdelegate]; return [appdelegate managedobjectcontext]; } 

note: replace <yourcontext> in first snippet maincontext


Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -