views:

228

answers:

2

If I want the user to be able to edit entries to a table with number data, (the user would click on a table cell, then on that child view, they would enter a number, and return back to the main table view), I was thinking I would just add entries to a NSMutabaleArray. If so, when the user leaves the application, are those values still there? If they are, do I just need to also have a clear table method that releases the array? Thanks.

+2  A: 

Your app's data is not persisted automatically.

If you have a small amount of data, you can to write out a collection such as an array to a Property List (plist) file in your app's Documents directory.

If you have a large amount of data, I would recommend using Core Data.

gerry3
A: 

The quick and dirty way is to use an NSKeyedArchiver to write the NSArray out to a file. You'll then have to read the data from the file back into your NSArray when the App launches.

Here's a snippet:

This gets the document path:

- (NSString*)pathForDataFile
{
    //Get the path of the Documents directory
    NSArray* paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );
    NSString* documentsDirectory = [paths objectAtIndex: 0]; //Path to the documents directory

    //Get the path to my file in /Documents  
    NSString* documentsPath = [documentsDirectory stringByAppendingPathComponent: 
             [NSString stringWithFormat: @"%@.plist", @"FileName"]];

    return documentsPath;
}

These will save and load:

- (BOOL)saveDataToDisk
{
    NSString* path = [self pathForDataFile];

    NSMutableDictionary* rootObject = [NSMutableDictionary dictionary];

    if ( self.yourArray )
     [rootObject setValue: self.powerListCollection.items forKey: kYourKey];

    [NSKeyedArchiver archiveRootObject: rootObject toFile: path];

    return YES;
}

-

- (BOOL)loadDataFromDisk
{
    NSString* path = [self pathForDataFile];
    NSFileManager* manager = [NSFileManager defaultManager];

    if ( [manager fileExistsAtPath: path] )
    {
     NSLog( @"Saved data found, loading data from %@", path );

     NSMutableDictionary* rootObject = nil;
     rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile: path]; 

     NSArray* self.yourArray = [rootObject objectForKey: kYourKey];

    }
    else
    {
     NSLog( @"No saved data, initializing objects with default values." );
    }

    return YES;
}

Note that you'll need to retain whatever you get back from objectForKey:

jessecurry