I’ve been asked a few times now how to load a file in an iOS application programmatically. It’s pretty easy, but many people overlook the fact that your compiled and built bundle may have a unique path upon installation on a device (or even your iPhone emulator).
You could do this opening and parsing using C standard libriaries (i.e. fopen(…), fread(…), etc…) but this raises two issues: unknown file location and not sticking with Objective-C standards. If you’re writing in Objective-C code, why hack around avoiding tools that already exist for you that can do all that extra work for you? Embrace Objective-C and solve the other little problems associated with reading/parsing performance!
The following code assumes you have your application ready to go and you have a file titled “SampleText.txt” with UTF-8 encoding. Don’t forget this file must be in your project’s path – it has to be included in your project by adding the file through XCode!
// Attempt to open a file of name "SampleText" with extension "*.txt"
NSString *FilePath = [[NSBundle mainBundle] pathForResource:@"SampleText" ofType:@"txt"];
if(FilePath == nil)
return -1;
// Load the file's contents into an NSString object; note that we parse the file as a UTF-8 encoding format
NSString* FileContent = [NSString stringWithContentsOfFile:FilePath encoding:NSUTF8StringEncoding error: nil];
if(FileString == nil)
return -1;
// Segment the file into lines
NSArray* FileStrings = [FileString componentsSeparatedByString:@"\n"];
// For each line within this array, etc...
for(NSString* LineString in FileStrings)
{ /* Do your work here! */ }