0

I'm having trouble with storing my NSMutableArray which holds some objects. Inside those objects there is also a NSMutableArray which holds also some objects.

For example: NSMutablearray "cars" --> NSObject "Porsche" ---> NSMutableArray "Parts" ---> NSObject "Tires"

And now i want to save the first Array "cars", so when i close the app and open it again, the array is still there. I read a few options - for example NSUserDefaults. I tried it, but it doesn't work.

Can someone help/teach me how to store a NSMutableArray like this?

Thanks

EDIT

If this is a duplicate, can someone show me how to do it?? Because i tried almost every Code i found on google. No code worked.

Kara
  • 6,115
  • 16
  • 50
  • 57
Mike_NotGuilty
  • 2,253
  • 5
  • 32
  • 64

1 Answers1

0

If you store an array either in a plist or in NSUserDefaults it is always immutable. You have to make it mutable after reading it out. With a simple array this is trivial.

NSMutableArray *mutable = [arrayFromUserDefaults mutableCopy];

or

NSMutableArray *mutable = [NSMutableArray arrayWithArray:arrayFromUserDefaults];

However, in a hierarchy like you describe it becomes more complicated. Essentially you have to iterate through the entire hierarchy and create mutable arrays where necessary.

Please note that neither plist nor user defaults can store your NSObject. You will have to convert it into an NSDictionary, with keys like "name" and "parts" to hold name string or parts array.

NSMutableArray *mutable = [NSMutableArray array];
for (NSDictionary *car in arrayFromUserDefaults]) {
    NSArray *immutableParts = car[@"parts]; 
    NSMutableArray *parts = [immutableParts mutableCopy];
    [mutable addObject:@{"name":car[@"name"], @"parts":parts}];
}

You can see how ridiculous this gets... I think this is both very cumbersome and unnecessary. Instead you should move to some kind of object graph, such as Core Data.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • It works for me now!! using this code: [Here](http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults) i had a stupid error in my code. – Mike_NotGuilty Nov 22 '13 at 13:13
  • The is very similar to my answer. You should accept it by ticking the checkmark. – Mundi Nov 22 '13 at 18:45