Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store custom objects with struct in Coredata

I have to store a custom class object to Coredata. The problem is my custom class contains structs,enum etc.I tried following method.

-(void)encodeWithCoder:(NSCoder *)encoder .

But am getting this error

[NSKeyedArchiver encodeValueOfObjCType:at:]: this archiver cannot encode structs'

What is the best practice to store this object to Coredata. Please help me.

like image 312
S.P. Avatar asked Aug 16 '10 10:08

S.P.


2 Answers

You can wrap the struct in a NSData, ie

To encode with archiver

[coder encodeObject:[NSData dataWithBytes:&my_struct length:sizeof(my_struct)] 
             forKey:@"my_struct"];

and to decode with archiver

NSData *data = [coder decodeObjectForKey:@"my_struct"];
[data getBytes:&my_struct length:sizeof(my_struct)];
like image 180
epatel Avatar answered Nov 14 '22 23:11

epatel


You should have a custom implementation of the NSCoding protocol in your custom class. In your own implementations of -[initWithCoder:] and -[encodeWithCoder:], you can then encode/decode the struct objects in any way you please.

On way to do this would be to call [coder encodeObject:[NSValue valueWithBytes:&yourStructVariable objCType:@encode(struct YourStructName)] forKey:@"someKey"]; in -[encodeWithCoder:] and do the equivalent decoding in -[initWithCoder:].

You can then just store the class objects as transformable in Core Data.

like image 24
mrueg Avatar answered Nov 14 '22 22:11

mrueg