Saving a NSArray

3 Solutions Collect From Internet About “Saving a NSArray”

NSArray provides you with two methods to do exactly what you want: initWithContentsOfFile: and writeToFile:atomically:

A short example might look like this:

//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];

//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
    //Array file didn't exist... create a new one
    yourArray = [[NSMutableArray alloc] initWithCapacity:10];

    //Fill with default values
//Use the content
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];

You could implement NSCoding on the objects the array contains and use NSKeyedArchiver to serialize/deserialize your array to disk.

BOOL result = [NSKeyedArchiver archiveRootObject:myArray toFile:path];

The archiver will defer to your NSCoding implementation to get serializable values from each object and write a file that can be read with NSKeyedUnarchiver:

id myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

More info in the serialization guide.

This would seem to be a problem most suited to Core Data as this will deal with all the persistent object data. When you retrieve you data it will return an NSSet, which is unsorted so you will have to have some way of sorting the data in the array such as a unique id number assocaited with each object you create.