Quote:
Originally Posted by loddy1234
I have some data stored in a NSMutableArray as NSNumbers. how can i save the mutable array? It is declared in the app delegate so I know I can use the
Code:
- (void)applicationWillTerminate:(UIApplication *)application {
}
to save it, and I can use the
Code:
- (void)viewDidLoad {
}
to load it but what code do I use in the applicationWillTerminate method to save it?
|
I would advise against saving in applicationWillTerminate. That method doesn't get called under OS 4.x
I would suggest saving your array every time it changes.
NSUserDefaults would work quite nicely.
Code:
#define K_ARRAY_KEY @"array_key"
Define numberArray as a retained property of the object that needs to use it, or your app delegate,
if you need access to it throughout your app.
Code:
- (void) saveData
{
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: self.numberArray forKey: K_ARRAY_KEY];
[defaults synchronize];
}
//Add this code to your applicationDidFinishLaunching/application:didFinishLaunchingWithOptions:
//method (or viewDidLoad, if you just need the array in a view controller)
Code:
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSArray* tempArray = [defaults objectForKey: K_ARRAY_KEY];
//the object comes back from user defaults as an NSArray, so copy it to a mutable array
self.numberArray = [NSMutableArray arrayWithCapacity: [tempArray count]];
[self.numberArray setArray: tempArray];
Note that saving a container object like an array to user defaults only works if every object in the array is a "plist" object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary).