Writing and reading text files on the iPhone

前端 未结 2 804
悲哀的现实
悲哀的现实 2020-12-09 13:17

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 UIT

相关标签:
2条回答
  • 2020-12-09 14:21

    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"];
    
    0 讨论(0)
  • 2020-12-09 14:23

    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];
    }
    
    0 讨论(0)
提交回复
热议问题