I am new to iPhone development and I am using XCode 4.2 I am trying to save an NSMutable array so that when I close the application and reopen it , the data will still be there I am using these two functions :
-(void)saveData{
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
- (void)loadData
{
data = [NSKeyedUnarchiver unarchiveObjectWithFile:self.dataFilePath];
}
but I found two major issues : 1- when I switch views and come back , the data is gone 2- when I completely exit the application (ie I double click on the Main button and remove it from the list of running application) the data is not erased as well
I found that I can use these two NSMutableArray methods : writeToFile
and initWithContentsOfFile
but I don t know where to call them (is it when I add items to the UITableView ? in the viewDidLoad
?
can somebody give me a sample code?
Thanks in advance
For saving an array use writeToFile:atomically:
method. It will save your NSArray
content as plist file. For load an array from plist file, use initWithContentsOfFile:
method.
Please note, that these methods will be able to save your stuff, only if your array has the following class instances NSString
, NSData
, NSDate
, NSNumber
NSArray
, or NSDictionary
as items.
you can call save/load methods like following
// in view controller implementation
- (void) saveData {
[self.theArray writeToFile: self.filePath automatically:NO];
}
- (void) loadData {
self.theArray = [NSArray arrayWithContentsOfFile: self.filePath];
}
- (void) viewDidLoad {
[super viewDidLoad];
[self loadData];
}
- (void) viewWillDisappear: (BOOL) animated {
[super viewWillDisappear: animated];
[self saveData];
}
// in the UIApplicationDelegate implementation
- (void)applicationWillResignActive:(UIApplication *)application {
[myCustomController saveData];
}
The problem is that when those 2 actions happen, saveData is not getting called. Therefore I would suggest saving your data on the AppDelegate on this method to solve problem 2 (exit app)
- (void)applicationDidEnterBackground:(UIApplication *)application
{
//Save data
}
As for problem 1 (when switching views), you just need to call your saveData on this method on your viewController:
- (void)viewWillDisappear:(BOOL)animated
{
//Save data
}
Hope that helps.
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.