iosobjective-c

Reading a text file and turning it into a string


I have added a text file to Xcode, now I want to make a string with it. How do I load it and put it into a string?

NewsStory1.txt is the file, and I'm using Obj-C.


Solution

  • NSString *path = [[NSBundle mainBundle] pathForResource:@"NewsStory1" ofType:@"txt"];
    NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    

    See Apple's iOS API documentation for NSString, specifically the section "Creating and Initializing a String from a File"