Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store NSArray In Core Data Sample Code?

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!

like image 417
Stunner Avatar asked Dec 28 '10 14:12

Stunner


People also ask

Can you store an array in Core Data?

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.

How do you declare NSArray in Objective-C?

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];

What is transformable in Core Data?

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.


1 Answers

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]; } 
like image 147
Resh32 Avatar answered Sep 26 '22 14:09

Resh32