Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing and reading text files on the iPhone

As a practice, I am trying to write an app similar to the built-in notes app.
But I cannot figure out how to save the file and display it in a UITableView.
Right now, I have a UITextView that the user can type in. I also have a save button.
When the user taps the save button, I want to save it, and later have it displayed in a table view.
I am very lost so if you know of any relevant tutorials etc. it would be greatly appreciated.

like image 368
tallen11 Avatar asked Feb 11 '11 00:02

tallen11


2 Answers

As noted by the commenters in the real world, you're definitely going to want to look at Core Data or some other data persistence strategy. If you're dead set on pursuing this as a learning experience, something like this should solve your problem:

- (void)writeStringToFile:(NSString*)aString {

    // Build the path, and create if needed.
    NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* fileName = @"myTextFile.txt";
    NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

    if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
        [[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
    }

    // The main act...
    [[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}

- (NSString*)readStringFromFile {

   // Build the path...
   NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
   NSString* fileName = @"myTextFile.txt";
   NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];

   // The main act...
   return [[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding] autorelease];
}
like image 103
Matt Wilding Avatar answered Nov 07 '22 23:11

Matt Wilding


The easiest way to save text is using NSUserDefaults.

[[NSUserDefaults standardUserDefaults] setObject:theText forKey:@"SavedTextKey"];

or, if you want to have the user name each "file" or be able to have multiple files

NSMutableDictionary *saveTextDict = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedTextKey"] mutableCopy] autorelease];
if (saveTextDict == nil) {
    saveTextDict = [NSMutableDictionary dictionary];
}

[saveTextDict setObject:theText forKey:fileName];
[[NSUserDefaults standardUserDefaults] setObject:saveTextDict forKey:@SavedTextKey"];
like image 1
Ray Lillywhite Avatar answered Nov 07 '22 22:11

Ray Lillywhite