contentOfFile路径给出null [英] contentOfFile path gives null

查看:87
本文介绍了contentOfFile路径给出null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将txt文件中的所有文本都转换为字符串,但如果我尝试使用NSlog()这个字符串,我会得到null。我认为这是因为我试图获取文件的路径,但我似乎无法弄清楚路径有什么问题。我知道我得到了正确的navigationItem.title,所以这不是问题所在。文本文件位于名为Øvelser/ Text /nameOfExercise.txt的子文件夹的主包中。我在下面粘贴了我的代码:

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


推荐答案

你需要使用 NSBundle 方法来获取相对于bundle的路径。此问题类似并将此作为创建路径的一种方式:

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

这篇关于contentOfFile路径给出null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆