2012-04-02 7 views
1

私は文字列にtxtファイルからすべてのテキストを取得しようとしていますが、NSlog()をこの文字列にしようとするとnullが返されます。私はそれがファイルを取得しようとしているパスのためだと思うが、私はパスで何が間違っているのか分からないようだ。私は正しいnavigationItem.titleが得られることを知っているので、それは問題ではありません。テキストファイルはメインバンドルのØvelser/ Text/"nameOfExercise" .txtというサブフォルダにあります。私は以下の私のコードを貼り付けていますcontentOfFileパスが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

何かが間違ってファイルを読み込む起こっているので、あなたが戻ってnilを取得しています。エラーオブジェクトへのポインタを渡すと、エラーの詳細が記入され、ログに記録すると何が問題になるかがわかります。エラー情報を無視しないでください。

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

NSStringには、パスを操作するための素敵な方法がたくさんあります。使用する必要があります。特に、stringByAppendingPAthComponentsstringByAppendingPathExtensionを使用してパスを構築します。

関連する問題