1

I'm trying to get all the text from a txt file into a string, but if I try to NSlog() this string, i get null. I think it's because of the path i'm trying to get the file at, but I can't seem to figure out what is wrong with the path. I know that i get the right navigationItem.title, so that is not the problem. The text file is in the main bundle in a subfolder called Øvelser/Text/"nameOfExercise".txt. I have pasted my code below:

- (void)viewDidLoad
{
[super viewDidLoad];

//Read from the exercise document
NSString *path = [[@"Øvelser/Text/" stringByAppendingString:self.navigationItem.title] stringByAppendingString:@".txt"];

if(path)
{

    _exerciseDocument = [NSString stringWithContentsOfFile:path encoding: NSUTF8StringEncoding error:nil];
    NSLog(@"%@", _exerciseDocument);
}
else 
{
    NSLog(@"error");
}
}
Niels Sønderbæk
  • 3,487
  • 4
  • 30
  • 43

2 Answers2

1

You need to use NSBundle methods to get paths relative to the bundle. This question is similar and gives this as a way of creating the path:

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
NSString *filePath = nil;

if (filePath = [thisBundle pathForResource:@"Data" ofType:@"txt" inDirectory:@"Folder1"])  {

    theContents = [[NSString alloc] initWithContentsOfFile:filePath];

    // when completed, it is the developer's responsibility to release theContents
Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

You are getting nil back because something is going wrong reading the file. If you pass a pointer to an error object, it will get filled in with error details and that will tell you what is going wrong if you log it. Don't ignore error information.

NSError* error = nil;
 _exerciseDocument = [NSString stringWithContentsOfFile: path 
                                               encoding: NSUTF8StringEncoding  
                                                  error: &error];
if (_exerciseDocument == nil)
{
     NSLog(@"Error: %@", error);
}
else
{
     // success
} 

NSString has lots of lovely methods for manipulating paths and you should use them. In particular construct your paths by using stringByAppendingPAthComponents and stringByAppendingPathExtension.

JeremyP
  • 84,577
  • 15
  • 123
  • 161