Monday, February 21, 2011

How to get the contents of a text file (stored locally in the documents directory) into an NSString?

How to retrieve the contents of a TEXT FILE stored locally in the documents directory?

From stackoverflow
  • Assuming the text is UTF-8 encoded:

    NSData *textFileData = [NSData dataWithContentsOfFile:pathToTextFile];
    NSString *textFileString = [NSString stringWithUTF8String:[textFileData bytes]];
    
  • You can also use this NSString class method (assuming the text is UTF-8):

    NSString *content = [NSString stringWithContentsOfFile:pathToTextFile encoding:NSUTF8StringEncoding error:&error];
    

    error should be a pointer to an NSError object.

0 comments:

Post a Comment