Reading a textfile

by

Having a text for the app, for instance the help, the best you can do is making a text file adding this to your project and reading the textfile using code. This way, a mispelled word is easily replaced without disrupting the code and the textfile is also much more readable then hard coded text in code.

This is how you read the textfile:

First get at your file:
NSString *pathNameString = @"points";
NSString *filePathString = [[NSBundle mainBundle] pathForResource:pathNameString ofType:@"txt"];

Then look if there is no mistake and read:
if (filePathString) {
NSString *myText = [NSString stringWithContentsOfFile:filePathString];
if (myText) {
NSArray *pointData = [myText componentsSeparatedByString:@","];

For numbers I use the separator “,” but anything can be used.
Now the pointData are NSStrings, so we have to get the values:
int i;
for (i=0; i< pointData.count ; i+=3 ){
float xData = (float)[[pointData objectAtIndex:i] floatValue ];

or intValue.
For a list of image names, the whitespaces must be cleaned:
NSString *imageSmallPage = [textImageObjectData objectAtIndex:i];
imageSmallPage = [imageSmallPage stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

Sometimes, for visibility you need returns (“\n”) in your textfiles, to get these out I used:

NSString * firstBounceString = [(NSString *)[pointArrayData objectAtIndex:i] stringByReplacingOccurrencesOfString:@"\n" withString:@"" ];
int bouncePointX = (int)[firstBounceString intValue ];

All these small details handling data have to be taken care of, otherwise you’ll get in some trouble later on…

Example code: again the dodecahedron, where I have a list of lines of the dodecahedron in a textfile, the points being found by algorithm.

Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.