Reading text from files in Cocoa

Despard

Registered
Hi,

I'm having some trouble with Xcode. What I need to do is read text from some files into a couple of arrays, then display the text on screen when I press a number key corresponding to the array index (it's a quiz-type game). This works when I run my program from Xcode, but doesn't when I double-click the built application in the Finder, even though the text files are in the same place.

Everything else about the program works except this (view is drawn, other commands work fine), and it's very frustrating. Here's the code I'm using to read the files:

Code:
- (void)setAnswersForQuestion:(NSNumber *)q
{
	NSString *fileName = [[@"q" stringByAppendingString:[q stringValue]] stringByAppendingString:@".txt"];
	NSLog(@"%@",fileName);
	
	answers = [[NSString stringWithContentsOfFile:fileName] componentsSeparatedByString:@"\n"];
	[answers retain];
	NSLog(@"%@",answers);
}

The files are called q1.txt, q2.txt, etc. I realise that a better way to do this would be to add the files directly to my project... but how do I tell the application where to find them then?

Thanks for any help! :)
 
Where are the files located in relation to your .app?

Code:
[[NSBundle mainBundle] bundlePath]
returns the path to your .app. If they're stored in your .app's Resources folder, you can use
Code:
[[NSBundle mainBundle] pathForResource:@"q1" ofType:@"txt"]
to get the full path of a file.
 
Ha! That's it. I forgot about bundles. Still new to Cocoa programming.

Thanks very much for your help! :D
 
Back
Top