안녕하세요 모두 에뮬레이터에서 꽤 잘 작동하는 프로그램을 작성했습니다. 그러나 프로젝트를 자체 장치에 업로드하면 파일을 읽고 항목을 표시 할 수 있지만 파일을 지우고 다시 쓸 때 작업을하지 않습니다.txt 파일 쓰기는 에뮬레이터에서 작동하지만 실제 장치에서는 작동하지 않습니다. xcode
이 문제를 해결할 수있는 방법은 무엇입니까?
안녕하세요 모두 에뮬레이터에서 꽤 잘 작동하는 프로그램을 작성했습니다. 그러나 프로젝트를 자체 장치에 업로드하면 파일을 읽고 항목을 표시 할 수 있지만 파일을 지우고 다시 쓸 때 작업을하지 않습니다.txt 파일 쓰기는 에뮬레이터에서 작동하지만 실제 장치에서는 작동하지 않습니다. xcode
이 문제를 해결할 수있는 방법은 무엇입니까?
앱 번들에 파일을 쓰려고하는 것 같습니다. 보안상의 이유로 Apple은 번들을 만지지 못하게합니다. 당신의 파일은 샌드 박스
복사 된 파일,
편집 : 여기
일부 코드 주어진 디렉토리에 번들에서 파일을 복사 (일부 오타 오류가있을 수, 엑스 코드에서 실행하지 않았다) 문서 디렉토리. 이 코드는 매번 Documents 디렉토리의 파일을 무시하므로주의하십시오. 당신이 복사 한 파일을 작업 할 때NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *fileDirectory = [documentsDirectory stringByAppendingPathComponent:@"MyDirectory"];
// Create folder if it does not exist
BOOL isDirectory;
if (![[NSFileManager defaultManager] fileExistsAtPath:fileDirectory isDirectory:&isDirectory])
{
NSError *error;
[[NSFileManager defaultManager] createDirectoryAtPath:fileDirectory withIntermediateDirectories:NO attributes:nil error:&error];
if(error)
{
NSLog(@"Error creating folder : %@",error.localizedDescription);
return;
}
else
{
NSLog(@"Folder created");
}
}
// Save to disk
NSString *filePathOnDisk = [fileDirectory stringByAppendingPathComponent:@"fileInSandbox.foo"];
NSString *pathFromBundle = [[NSBundle mainBundle] pathForResource:@"fileFromBundle" ofType:@"foo"];
NSData *fileData = [NSData dataWithContentsOfFile:pathFromBundle];
NSError *error;
if (![fileData writeToFile:filePathOnDisk options:NSDataWritingAtomic error:&error])
{
NSLog(@"Error writing file : %@", error.localizedDescription);
}
else
{
NSLog(@"File saved to disk successfully");
}
그런 다음, 우리가 filePathOnDisk
에서 만든 경로를 사용합니다. 파일 관리와 관련된 문서를 다시 읽고 파일 작업에 대해 이해하십시오.
코드를 작성할 수 있습니까 – Sauvage
[[NSFileManager defaultManager] removeItemAtPath : filePath 오류 : nil]; [[NSData data] writeToFile : 원자적인 filePath : 예]; NSFileHandle * handle = [NSFileHandle fileHandleForWritingAtPath : filePath]; [handle truncateFileAtOffset : [handle seekToEndOfFile]]; [writeData를 처리하십시오 : [something dataUsingEncoding : NSUTF8StringEncoding]]; – albatross
'NSString * directory = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) [0];'을 디렉토리로 사용하십시오. 그렇다면 전체 경로는 다음과 같습니다.'directory = [directory stringByAppendingPathComponent : fileName];' – Sauvage