Reputation: 23
I have created an iPhone application, I would like to be able to load in a batch of data with the application, but to not store all of the data in the .h or.m files.
Is there a way to attach a text file as a resource in the application, and then load that text file into an NSString in the iPhone application.
I am looking to include this text data file as part of the iPhone application when it is complied, but to access the data at run time.
thanks!
Upvotes: 2
Views: 346
Reputation: 15099
Here is an example doing exactly that: http://iphoneincubator.com/blog/data-management/how-to-read-a-file-from-your-application-bundle
Relevant code from above link:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];
if (filePath) {
NSString *myText = [NSString stringWithContentsOfFile:filePath];
if (myText) {
textView.text= myText;
}
}
Upvotes: 1
Reputation: 85522
Sure, it's easy. Just add your .txt files to your project (drag them to the Files tree). To access them, you need to first get the path:
NSString *path = [[NSBundle mainBundle] pathForResource: @"filename" ofType: @"txt"];
Then load the string:
NSError *error = nil;
NSString *fileData = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: &error];
Upvotes: 5