我将尝试将一个纯文本文件保存到iOS 7中的“文档”目录中。以下是我的代码:
//Saving file
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSString *url = [NSString stringWithFormat:@"%@", urls[0]];
NSString *someText = @"Random Text To Be Saved";
NSString *destination = [url stringByAppendingPathComponent:@"File.txt"];
NSError *error = nil;
BOOL succeeded = [someText writeToFile:destination atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (succeeded) {
NSLog(@"Success at: %@",destination);
} else {
NSLog(@"Failed to store. Error: %@",error);
}
我遇到的错误如下:
2013-10-13 16:09:13.848 SavingFileTest[13675:a0b] Failed to store. Error: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x1090895f0 {NSFilePath=file:/Users/Username/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/F5DA3E33-80F7-439B-A9AF-E8C7FC4E1630/Documents/File.txt, NSUserStringVariant=Folder, NSUnderlyingError=0x10902aeb0 "The operation couldn’t be completed. No such file or directory"}
我弄不清楚为什么在模拟器上运行时会出现这个错误。如果我使用NSTemporaryDirectory(),就能正常工作。