I have been searching for some sample code on how to store an NSArray
in Core Data for awhile now, but haven't had any luck. Would anyone mind pointing me to some tutorial or example, or better yet write a simple sample as an answer to this question? I have read this but it doesn't show an example of how to go about implementing a transformable attribute that is an NSArray
. Thanks in advance!
There are two steps to storing an array of a custom struct or class in Core Data. The first step is to create a Core Data entity for your custom struct or class. The second step is to add a to-many relationship in the Core Data entity where you want to store the array.
In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];
When you declare a property as Transformable Core Data converts your custom data type into binary Data when it is saved to the persistent store and converts it back to your custom data type when fetched from the store. It does this through a value transformer.
If you really need to do it, then encode as data. I simply created a new filed called receive
as NSData (Binary data).
Then in the NSManagedObject implementation:
-(void)setReceiveList:(NSArray*)list{ self.receive = [NSKeyedArchiver archivedDataWithRootObject:list]; } -(NSArray*)getReceiveList{ return [NSKeyedUnarchiver unarchiveObjectWithData:self.receive]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With