I have searched everywhere and tried lots of code but nothing seems to be working for me. All I need to do is to load (on viewDidLoad) a text field and save it when a button is
Use the NSUserDefaults class which was specifically made for this scenario.
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
// saving a NSString (you usually do this when the value is being submitted)
[defs setObject:textField.text forKey:@"aKey"];
[defs synchronize]; //this commits the new value - shouldn't be necessary because this is doe automatically, but just in case...
// loading a NSString (you usually do this on viewDidLoad)
testField.text = [defs objectForKey:@"aKey"];
The value is stored across sessions.
You can store other value types as well (other than NSString).
Use a different key for each field for which you want to store values.
This can also be used to store app configurations/options/etc
Using an SQLite database:
-(IBAction) checkNotes{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT Notes FROM NotesTable WHERE UserID = (\"%@\")", userID.text];
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *notesField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
Notes.text = notesField;
[notesField release];
}else{
Status.text = @"Not found";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
You can play around a little bit and adapt this code to your needs. For implementing SQLite3, check the net. But it will help you much in the future I guess. I think it would be the most flexible, because it will also allow you to create relational databases.
Create a NSMutableDictionary as property and ...
when your button is clicked:
-(IBAction)buttonClicked:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *devicePath = [documentsDirectory stringByAppendingPathComponent:@"yourfile.txt"];
[self.dictionary setObject:self.textField.Text key:@"textField"];
[self.dictionary writeToFile:devicePath atomically:YES];
}
On your viewDidLoad, you can get the value of the file by:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"youefile"
ofType:@"txt"];
self.dictioary = [[[NSMutableDictionary alloc] initWithContentsOfFile:filePath] autorelease];