2013-05-22 6 views
2

텍스트 편집기 응용 프로그램을 작성하고 NSString을 문서 폴더의 파일에 NSData로 저장하려고합니다. 예를 들어 "myText.java"파일을 저장할 수 있기를 원합니다. ".응용 프로그램 문서 폴더에서 문서 저장 및 가져 오기

내 코드가 시뮬레이터에서 작동합니다. 그러나, 장치에서 파일을 만들 것으로 보인다지만, 나중에 파일에서 데이터를로드하려고 할 때 나는 아무것도 얻지 못합니다.

장치의 문서 디렉토리를 사용하려면 일부 프로젝트 설정을 설정해야합니까, 아니면 코드가 잘못 되었습니까?

여기 내 가게 코드 :

-(void) saveFile:(NSString*)file{ 
    if (![file isEqual:@"Empty"]) { 
     NSArray *paths = NSSearchPathForDirectoriesInDomains 
     (NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:file]; 

     [[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil]; 
     NSLog(@"File: %@", fullFilePath); 
     //Above LOGS: /var/mobile/Applications/2310F459-282C-4488-AE24-D5795168F85A/Documents/fg 

     //save content to the documents directory 
     NSLog(@"Saving: %@", codeView.text); 
     // Logs the data i want to store 
     [[codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES]; 
    } 
} 

가 여기 내로드 파일의 코드입니다

-(void) loadFile:(NSString*)filename{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains 
    (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    //make a file name to write the data to using the documents directory: 
    NSString *file = [documentsDirectory stringByAppendingPathComponent:filename]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:file]) { 
     NSLog(@"File found"); 
     //Yes the file is found 

     theDelegate.fileData = [NSData dataWithContentsOfFile:file]; 
     NSLog(@"Data:%@",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:file] encoding:NSASCIIStringEncoding]); 
     // On device and simulator data is found 

     [theDelegate.codeView setText:[[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]]; 
     //codeView does not get updated with the data. 
     //NSLog([[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]); 
     [theDelegate setTitle:filename]; 
     [theDelegate setHasOpenFile:YES]; 
     [theDelegate.codeView setEditable:theDelegate.hasOpenFile]; 
     [theDelegate.codeView setNeedsDisplay]; 
     [self setLanguage:filename]; 
    }else{ 

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File error!" message:@"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil, nil]; 
     [alert show]; 
    } 
} 
+0

'writeToFile : atomically :'의 반환 값을 확인하십시오. 또한 파일을'myText.java'로 저장하길 원하지만 로그는'file'이 단지'fg'라는 것을 보여줍니다. – rmaddy

+0

내가 어디가 잘못되었는지 찾으려고하지만, 그냥 제쳐두고,이 코드는 다소 끔찍합니다. 'saveFile'는 파일명에'file'을 사용하고,'loadFile'은 이름에'filename'을 사용하고, 전체 경로에는'file'을 사용합니다. 이것은 오류를 묻습니다. – uvesten

+0

귀하의 의견에 감사드립니다, 나는 그것을 돌볼 것입니다 –

답변

2

아니요, 문서 디렉토리를 사용하도록 설정하지 않아도됩니다. 어쨌든 코드에 오류가 있거나 없을 수 있습니다. 어떤 경우에는 읽기 어렵고별로 깨끗하지는 않습니다. (이 말에 사과드립니다.)

모든 것을 한 번만 해보십시오. 나는 당신의 코드를 약간 다시 작성하여 그것을 지우는 자유를 얻었다. 그런 다음 휴대 전화의 샘플 앱으로 테스트 해 보았는데 완벽하게 작동합니다.

코드 재 작성 :

-(void) saveFile:(NSString*)filename{ 
    if (![filename isEqual:@"Empty"]) { 

     NSString *fullFilePath = [self getFullFilePath:filename]; 

     [[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil]; 
     NSLog(@"File: %@", fullFilePath); 

     //save content to the documents directory 
     NSLog(@"Saving: %@", self.codeView.text); 
     // Logs the data i want to store 
     [[self.codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES]; 
    } 
} 

위의 코드는 도우미 함수를 추가 한 후, 괜찮습니다. 참조가 약한 경우 기존 코드에서

-(void) loadFile:(NSString*)filename{ 

    NSString *fullFilePath = [self getFullFilePath:filename]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:fullFilePath]) { 
     NSLog(@"File found"); 
     //Yes the file is found 

     NSLog(@"Data:%@",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]); 
     // On device and simulator data is found 

     [theDelegate.codeView setText:[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]]; 

     [theDelegate setTitle:filename]; 
     [theDelegate setHasOpenFile:YES]; 
     [theDelegate.codeView setEditable:theDelegate.hasOpenFile]; 
     [theDelegate.codeView setNeedsDisplay]; 
     //[self setLanguage:filename]; 
    }else{ 

     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File error!" message:@"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil, nil]; 
     [alert show]; 
    } 
} 

theDelegate.fileData = [NSData dataWithContentsOfFile:file];에 문제가 발생했을 수 있습니다. 코드 뷰에 코드가 항상 있다고 가정하기 때문에 먼저 멤버 변수에 코드를 저장하는 것이 필요하지 않습니다. 또한 이로 인해 더 많은 버그가 발생할 수 있습니다.

다음은 도우미 함수이므로 버그가 발생할 수 있으므로 두 함수에서 똑같은 작업을 수행하지 마십시오.

-(NSString*) getFullFilePath:(NSString*)filename { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains 
    (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:filename]; 

    return fullFilePath; 

} 
+0

당신은 아마도 옳습니다. NSData 단계를 건너 뛰면 코드가 예상대로 작동합니다. BR –

1

당신이 loadFile:saveFile:에 전달 된 파일 이름이 정확히 같은 이다 돌보는, 대문자 포함? iOS는 대소 문자를 구별하며 SomeFile.txtsomefile.txt을 두 가지 다른 것으로 취급하는 반면, Mac OS X (및 확장, iOS 시뮬레이터)는 대소 문자를 구분하지 않는 파일 이름을 사용합니다.

+0

이것은 코멘트/질문, 대답이 아닙니다. – rmaddy