views:

177

answers:

4

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?

+1  A: 

The iPhone SDK is designed to store data using SQLite tables.

mcandre
+2  A: 

So long as the objects in the array implement NSCoding (NSString and NSValue do; if you're storing your own objects it's relatively straightforward), you can use:

[NSKeyedArchiver archiveRootObject: array toFile: filePath];

to save and:

array = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath];

to load.

You can similarly load/save to NSData.

dmercredi
+3  A: 

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.

Jordan
+1  A: 

You can use NSPropertyListSeralization, since NSArray is a type of property list. You can find more information here.

Itay