contentOfFile路径给出null

时间:2012-04-02 15:37:42

标签: objective-c ios5 xcode4.2 filepath

我正在尝试将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");
}
}

2 个答案:

答案 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有很多可爱的方法来操作路径,你应该使用它们。特别是使用stringByAppendingPAthComponentsstringByAppendingPathExtension构建路径。