2012-04-02 8 views
1

txt 파일의 모든 텍스트를 문자열로 가져 오려고하지만이 문자열을 NSlog()로하면 null이됩니다. 나는 그것이 파일을 얻으려고하는 길 때문에 생각한다. 그러나 나는 그 길에 무엇이 잘못되었는지를 알 수 없다. 나는 그것이 올바른 navigationItem.title을 얻는다는 것을 안다. 그래서 그것은 문제가 아니다. 텍스트 파일은 메인 번들의 하위 폴더 인 Øvelser/Text/"nameOfExercise".txt에 있습니다. 당신은 번들에 상대 경로를 얻을 수 NSBundle 방법을 사용할 필요가contentOfFile path null 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

: 나는 아래에 내 코드를 붙여 넣은. 이 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을 사용하여 경로를 구성하십시오.