In this tutorial we will teach you how to save data and load data in iPhone applications.
This app will save the data before it closes and load the information back into the input box when the application starts.
Step One
First create a view based application and name it something like saveIt.
Go to the saveItViewController.h and add the following code:
#import
@interface saveItViewController : UIViewController {
UITextField *textField;
}
@property(nonatomic, retain)IBOutlet UITextField *textField;
-(NSString *)PathOfFile;
-(void)applicationWillTerminate:(NSNotification*)notification;
@end
Notice the word notification, this is how objects communicate to each other, there will be another tutorial on this topic later.
Step Two
Next open the interface builder by double clicking saveItViewController.xib,
Add a text input box,
click on the file's owner and hold down ctrl, drag the line to the input box and select textField.
Step Three
Next go to the saveItViewController.h and add the following code:
@implementation saveItViewController
@synthesize textField;
-(NSString *)PathOfFile{
NSArray *thePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *theFolder = [thePath objectAtIndex:0];
return [theFolder stringByAppendingFormat:@"theFile.plist"];
}
-(void)applicationWillTerminate:(NSNotification*)notification{
NSMutableArray *myArray = [[NSMutableArray alloc]init];
[myArray addObject:textField.text];
[myArray writeToFile:[self PathOfFile] atomically:YES];
[myArray release];
}
- (void)viewDidLoad {
NSString *pathToFile = [self PathOfFile];
if([[NSFileManager defaultManager] fileExistsAtPath:pathToFile]){
NSArray *array = [[NSArray alloc] initWithContentsOfFile:pathToFile];
textField.text = [array objectAtIndex:0];
[array release];
}
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:myApp];
[super viewDidLoad];
}
Delete all the comments before adding the above code (all the green text).
The function pathToFile is used to get the files directory.
The function application will terminate is used to save the information in the format of an array.
The viewDidLoad is used to load in the information when the application starts, the if statement checks to see if the saved file exists.
if it does not, a new file is created.
-- End of Tutorial --
Below is a video to guide you through this tutorial.