简体   繁体   中英

Saving a NSArray

I would like to save an NSArray either as a file or possibly use user defaults. Here's what I am hoping to do.

  1. Retrieve already saved NSArray (if any).
  2. Do something with it.
  3. Erase saved data (if any).
  4. Save the NSArray.

Is this possible, and if so how should I do this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM