Saving an NSMutableArray to Core Data

13,685

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.

Share:
13,685
gburgoon
Author by

gburgoon

I'm a young software developer looking for great business opportunities. I'm always looking to learn more about software development/methodlogies, and I try to push the boundaries of current software capabilities. Areas of most interest to me are video game, mobile, and web development.

Updated on June 05, 2022

Comments

  • gburgoon
    gburgoon almost 2 years

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

  • SinisterMJ
    SinisterMJ almost 15 years
    But here we have an array of simple strings - would you have to wrap each string in a managed object, or is there any kind of thin NSManagedObject wrapper around NSString already available?
  • gburgoon
    gburgoon almost 15 years
    How to you turn the array of strings to data?? (I found a workaround for this issue that involved me not having to use an array of strings, but I'm still curious for a solution)
  • Resh32
    Resh32 over 11 years
    The opposite is NSArray* array = [NSKeyedUnarchiver unarchiveObjectWithData:arrayData];
  • flypig
    flypig over 10 years
    The correct way is to create another entity table, and add a relationship between these two entities! I think it is a waste of time for archiving && unarchiving the array.
  • huggie
    huggie about 10 years
    Why is that adding another entity table and having the relationship is "better"? Is it because it's explicit?