Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding an NSMutableArray

I have an object containing various NSString objects and variables which I us NSCoding to archive to a file on the disk and later unarchive. So far everything has been working perfectly.

Today, I wanted to add an NSMutableArray to the object and tried to encode using the:

[encoder encodeObject:myArray ForKey:@"myArray"];

and later decode it using:

[self setMyArray:[decoder decodeObjectForKey:@"myArray"]];

It doesn't appear to be working, and while I don't get any errors in the encoding or decoding itself, I do get an error if I try to modify the value of the array after decoding from the file.

I'm sure I'm doing something completely wrong here, but not entirely certain what. I'm thinking perhaps it may have something to do with it not properly allocing during the unarchive.

Anything look blatantly obvious as the source of the problem?

like image 899
Greg Steiner Avatar asked Dec 26 '22 23:12

Greg Steiner


1 Answers

It doesn't appear to be working, and while I don't get any errors in the encoding or decoding itself, I do get an error if I try to modify the value of the array after decoding from the file.

Decoding an archive gives you immutable objects regardless of whether they were mutable or immutable when you encoded them. You're not doing anything particularly wrong -- it's working as advertised.

See this answer for another example of a similar problem, and a solution:

[self setMyArray:[[decoder decodeObjectForKey:@"myArray"] mutableCopy];
like image 177
Caleb Avatar answered Feb 03 '23 18:02

Caleb