2012-04-02 31 views
1

我想从一个txt文件中的所有文本转换为一个字符串,但如果我尝试NSlog()这个字符串,我得到null。我认为这是因为我试图获取文件的路径,但我似乎无法弄清楚路径有什么问题。我知道我得到正确的navigationItem.title,所以这不是问题。该文本文件位于称为Øvelser/ Text /“nameOfExercise”.txt的子文件夹的主包中。我已经粘贴下面我的代码:contentOfFile path给null

- (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

您需要使用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 
0

。如果你传递一个指向错误对象的指针,它将被填充错误细节,并且会告诉你如果你记录它会出现什么问题。不要忽略错误信息。

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

NSString有很多可爱的操作路径的方法,你应该使用它们。特别是使用stringByAppendingPAthComponentsstringByAppendingPathExtension构建您的路径。