Can NSManagedObject conform to NSCoding

后端 未结 3 621
心在旅途
心在旅途 2021-01-05 16:20

I need to transfer a single object across device. Right now I am converting my NSManagedObject to a dictionary , archiving it and sending as NSData. Upon receiving I am unar

3条回答
  •  青春惊慌失措
    2021-01-05 17:04

    This snippet below should do the trick. The main difference is to call super initWithEntity:insertIntoManagedObjectContext:

    - (id)initWithCoder:(NSCoder *)aDecoder {
       NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:];
    
       self = [super initWithEntity:entity insertIntoManagedObjectContext:nil];
       NSArray * attributeNameArray = [[NSArray alloc] initWithArray:self.entity.attributesByName.allKeys];
    
       for (NSString * attributeName in attributeNameArray) {
            [self setValue:[aDecoder decodeObjectForKey:attributeName] forKey:attributeName];
       }
       return self;
    }
    

    Above snippet will handle only the attributes, no relationships. Dealing with relationships as NSManagedObjectID using NSCoding is horrible. If you do need to bring relationships across consider introducing an extra attribute to match the two (or many) entities when decoding.

    how to obtain

    (based on a now unavailable post by Sam Soffes, code taken from https://gist.github.com/soffes/317794#file-ssmanagedobject-m)

    + (NSManagedObjectContext *)mainContext {
         AppDelegate *appDelegate = [AppDelegate sharedAppDelegate];
    return [appDelegate managedObjectContext];
    }
    

    Note: replace in the first snippet with mainContext

提交回复
热议问题