2013-04-09 2 views
1

이 코드를 사용하여 동일한 파일에 문자열을 10 번 작성했습니다. 그러나 모든 새로운 출시에 대해 이전 데이터를 덮어 씁니다. 이전 데이터에 새 데이터를 추가하고 싶습니다.NSDocumentDirectory에서 이전 파일 덮어 쓰기

[@"one" writeToFile:[self returnDocumentsDirectory] atomically:NO encoding:NSASCIIStringEncoding error:nil]; 


-(NSString *)returnDocumentsDirectory 
{ 
    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0]; 
    NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"]; 
    return filePath; 
} 

답변

2

를 사용하여 다음 코드는 파일에 여러 추가 작업에 대한 루프에서

NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *path = [DocumentsDirectoryPath objectAtIndex:0]; 
NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"]; 

// Create a FileHandle 
NSFileHandle *myHandle; 

넣어 다음 코드를 작성하는

// Check File Exist at Location or not, if not then create new 
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:[@"Your First String" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; 

// Create handle for file to update content 
myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; 

// move to the end of the file to add data 
[myHandle seekToEndOfFile]; 

// Write data to file 
[myHandle writeData: [@"YOUr Second String" dataUsingEncoding:NSUTF8StringEncoding]]; 

// Close file 
[myHandle closeFile];