我正在尝试将txt文件中的所有文本都转换为字符串,但如果我尝试使用NSlog()这个字符串,我会得到null。我认为这是因为我试图获取文件的路径,但我似乎无法弄清楚路径有什么问题。我知道我得到了正确的navigationItem.title,所以这不是问题所在。文本文件位于名为Øvelser/ Text /“nameOfExercise”.txt的子文件夹的主包中。我在下面粘贴了我的代码:
- (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");
}
}
答案 0 :(得分:1)
您需要使用NSBundle
方法来获取相对于捆绑的路径。这个question是类似的,并将其作为创建路径的一种方式:
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
答案 1 :(得分:0)
由于读取文件时出错,您的回复率为零。如果您将指针传递给错误对象,它将填入错误详细信息,并告诉您如果记录它会出现什么问题。不要忽略错误信息。
NSError* error = nil;
_exerciseDocument = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &error];
if (_exerciseDocument == nil)
{
NSLog(@"Error: %@", error);
}
else
{
// success
}
NSString有很多可爱的方法来操作路径,你应该使用它们。特别是使用stringByAppendingPAthComponents和stringByAppendingPathExtension构建路径。