I'm learning how to write simple Objective-C programs (without GUIs). I made a new xcode project and have the following files on the top-level directory:
main.m
data.txt
How can I get the contents of data.txt as an NSString for use in main.m?
I tried:
+ (NSString *)loadTextFileToString:(NSString*)fileDest {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileDest
ofType:@"txt"];
NSError *error = nil;
NSString *fileContent = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
if(error) {
NSLog(@"ERROR while loading from file: %@", error);
}
return fileContent;
}
And passing @"data" as the argument but it gives me the error:
ERROR while loading from file: Error Domain=NSCocoaErrorDomain Code=258 "The file name is invalid."
What is the correct way to do this?
Your code is actually totally correct. The problem is with your XCode project. When you run your program, it gets run from the "Products" directory, the location of which depends on your XCode settings. If you want the data.txt file to end up in the same place as the executable, so it can be found at runtime, you need to add the file to the "Copy Files" build phase, with the destination set to the "Products" folder:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With