5

I have this code below:

    NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"];
    NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
    NSError *error = nil;

    [textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]];
  • textviewerdownload is the textview displaying the text from the file. The actual file name is stored in an NSUserDefault called recentDownload.

  • When I build this, I click the button which this is under, and my application crashes.

  • Is there anything wrong with the syntax or just simple error?

Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
lab12
  • 6,400
  • 21
  • 68
  • 106
  • If there were a problem with the syntax, your code would not compile; you would not get to the stage of running it and seeing it crash. To debug a crash, use the debugger; it should be telling you how you crashed and where. – Peter Hosey Apr 26 '10 at 05:49

3 Answers3

9

The NSBundle class is used for finding things within your applications bundle, but the Documents directory is outside the bundle, so the way you're generating the path won't work. Try this instead:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask,
                                                     YES);

NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
jlehr
  • 15,557
  • 5
  • 43
  • 45
  • Ok I changed some of the coding.. My application still crashes.. Here is the code under my IBAction: http://www.heliotop.org/code.rtf Also how would I do an if statement, where if the recent file is not a file with the extension "txt", it would return, and if it was then result in an action.. – lab12 Apr 25 '10 at 21:07
6
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
    {
        NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
    }       

    //Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];

This worked for me

Anyway, thank you all..

iOS
  • 3,526
  • 3
  • 37
  • 82
2

For read/write from text file check this url.

tharinduNA
  • 580
  • 5
  • 12
KingofHeaven
  • 1,195
  • 3
  • 14
  • 27