[英]Empty documents directory after creating file with NSFileHandle
我正在为Apple Watch编写应用程序。 我正在使用以下方法(从SE答复 )来写入日志文件:
- (void) writeLogWith: (NSString *) content {
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"whathappened.md"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
return;
}
我通过插入手机并直接在手表上运行来运行它。 该函数肯定正在执行(我已经与调试器合作了),并且它也知道该文件存在并且不会反复尝试创建它。
Xcode告诉我该文件信息是:
Printing description of documentsDirectory:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents
Printing description of documentsDirectory:
(NSString *) documentsDirectory = 0x16d66890
Printing description of fileName:
(NSString *) fileName = 0x16d66950
Printing description of fileName:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents/whathappened.md
我想知道它是否写正确,但是当我查看容器时(遵循这些SE回答 ),documents目录为空。
我的问题是:我的文件去了哪里? 我怎么找到它?
我认为可能给您带来问题的是NSFileHandle
对象。 我已经将成千上万的文件写入documents文件夹,并且从未使用过NSFileHandle
。 只需使用NSString
上的内置方法即可将您的字符串写入文件路径。
尝试这个:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:@"whathappened"] stringByAppendingPathExtension:@"md"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
NSString *string = @"The String You Want To Write.";
NSError *error;
[string writeToFile:filePath atomically:false encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"There was an error writing file\n%@", error.localizedDescription);
}
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(@"File exists :)");
}
else {
NSLog(@"File does not exist :(");
}
根据其他研究,答案似乎是:
如果要在Apple Watch上存储文件,该文件将存储在其自己的容器中,该文件无法通过xcode看到。
实际上,它似乎与以下错误报告有关: https : //openradar.appspot.com/radar?id=5021353337946112(通过此SE查找): 如何使用Xcode6.2导出iOS应用程序的共享容器?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.