Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a NSArray

Tags:

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?

like image 660
Joshua Avatar asked Sep 28 '09 15:09

Joshua


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

Can NSArray contain nil?

arrays can't contain nil. There is a special object, NSNull ( [NSNull null] ), that serves as a placeholder for nil.

What is an NSArray?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.


1 Answers

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]; 
like image 175
rluba Avatar answered Oct 02 '22 13:10

rluba