How to store custom objects with struct in Coredata

后端 未结 3 1515
轮回少年
轮回少年 2020-12-10 17:38

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)encodeWit

相关标签:
3条回答
  • 2020-12-10 18:15

    With a struct, I think, it would be best to create a function that can encode and decode the struct, like any Objective-C object.

    With enums, I am not so sure. Enums are just numbers associated with a name, so just enode and decode them as a numbers.

    0 讨论(0)
  • 2020-12-10 18:30

    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)];
    
    0 讨论(0)
  • 2020-12-10 18:37

    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.

    0 讨论(0)
提交回复
热议问题