R – Is it possible to store an NSMutableArray together with all its contents into a file and restore it later from there

iphonepersistence

Some kind of serialization available in iPhone OS? Is that practically possible or should I quickly forget about that?

I am making a tiny app that stores some inputs in an NSMutableArray. When the user leaves, the inputs should stay alive until he/she returns to continue adding or removing stuff to/from that array.

When the app quits, there must be some way to store all the stuff in the array in a file. Or must I iterate over it, rip everything out and write it i.e. comma-separated somewhere, then the next time go in again, read the stuff in, and iterate over the lines in the file to make an array with that data? That would be hard like a brick. How to?

Best Solution

The easy way, since you already have an NSArray object is to write the array to disk using

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

and read it back in with:

- (id)initWithContentsOfFile:(NSString *)aPath

or

+ (id)arrayWithContentsOfFile:(NSString *)aPath

You can also use NSCoder.

You can probably search sof for the right code.

Related Question