mx_wmq
Last Updated: September 06, 2016
·
44.58K
· jfsagasti
U1b6bd8ad071161fb5bd43535867f4590

How to save a NSArray/NSMutableArray in Core Data

Any class you have which conforms to the NSCoding protocol can be serialized and archived in this way. NSArray/NSMutableArray already conform this protocol. Its important to say that all of objects of the array must conform too.

If you have in your model an entity with a property of type 'Binary Data', you can store in it the array data by doing:

[...]
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:TheArray];
myEntity.arrayProperty = arrayData;
[self saveContext]; //Self if we are in the model class
[...]

Then you can retrieve all the original array info by doing the opposite operation:

[...]
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:anEntity.arrayProperty];
[...]
Say Thanks
Respond

9 Responses
Add your response

1774

Thanks !! This post saved my life!

over 1 year ago ·
2657
U1b6bd8ad071161fb5bd43535867f4590

I'm glad to hear that! :)

over 1 year ago ·
3405

Why would you do that? Create new model for the NSArray entries?

over 1 year ago ·
7560
0 zpipybzmzvmco8las m8yxkm4befyqlavt02yxkyfay0 g mqvrx krk9sor0txgmkdsp v4d 3o

Awesome..

over 1 year ago ·
9151
333a334c7ef9850538f348f9868e1ef1

Thanks dude, this was really helpful.

over 1 year ago ·
11948
0 lnotmmq2rg7zyfwi51z3m2gsr6zbykwibpodmd gxiuqthy wtvycsqpze4wj efxbhune8c6wh8

thanks a lot..precise and great.. saved lot of my time

over 1 year ago ·
12533
9d241c2b6fe95e1b84d990c03934a33d normal

While this works perfectly.. It's possible to automate all of this. Just use a Core Data transformable. Core Data will use an NSUnarchiveFromDataTransformer by default which relies on NSArray conforming to NSCoding to automatically convert your NSArray to NSData. That way, you don't have to do any archiving or unarchiving yourself.

over 1 year ago ·
12534
U1b6bd8ad071161fb5bd43535867f4590

Great! Thanks for your contribution simonschellaert :)

over 1 year ago ·
28136

Yes, Its works for storing array of NSObject in transformable field.
but Is is possible to store array of NSManagedObject in transformable field?
i tried it but its giving an error.
please help me.
Thanks in advance.

9 months ago ·