contentOfFile path gives null

泪湿孤枕 提交于 2019-12-13 00:39:16

问题


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");
}
}

回答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



回答2:


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.



来源:https://stackoverflow.com/questions/9979321/contentoffile-path-gives-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!