Loading text data in an iPhone application
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 th开发者_开发知识库e 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!
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];
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;
}
}
精彩评论