Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an NSMutableArray to Core Data

Tags:

I want to add an NSMutableArray of NSStrings to one of my Entities in my core data model. The problem is that this isn't a supported type in Core Data.

I tried making a tranformable attribute, but the problem is that I see no way of turning a NSMutableArray to NSData, and then going from NSData, back to an NSMutableArray. Does anyone have an idea as to how this issue can be solved?

(I know I can archive the array, but I don't want to do that, I want it to be present in my model).

like image 358
gburgoon Avatar asked Jul 09 '09 13:07

gburgoon


People also ask

How do I save an object in Core Data?

To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core Data.

How do I save an array of objects 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.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray .


1 Answers

You could have a binary data attribute in your modeled object, archive the array to data, and hand it off to the object.

But I think the better way would be to have a to-many relationship, instead of using an array directly.

****Edit: Here's how to archive the array into NSData so that it can be used in your managed object***

NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:[NSArray arrayWithObjects:@"1",@"2", nil]]; 

Basically, any class you have which conforms to the NSCoding protocol can be archived in this way. NSArray/NSMutableArray already conform to it. They tell all of their objects to archive themselves, so they must conform too. And all of those objects' members must conform, etc. It's like a tree.

Since your array conforms, and it's an array of NSString (which also conforms), then you're golden.

like image 100
jbrennan Avatar answered Oct 13 '22 23:10

jbrennan