[英]iOS 8 writeToFile in Simulator
I'm trying to write a simple string to file, using the following code: 我正在尝试使用以下代码将简单的字符串写入文件:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = @"Test Content";
NSError *error = nil;
[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
NSLog(@"Error %@ %@", fileName, error);
But the file is'nt written and error is null. 但是未写入文件,错误为null。
I'm running the code in the iOS Simulator and expect the file to be written to a location like: /Users/user/Library/Developer/CoreSimulator/Devices/85DDC17D-A771-40D9-99BE-71FF6B60D2DF/data/Containers/Data/Application/BD30A945-25DB-4ECE-B7F7-E9C20C6691C7/Documents/textfile.txt (the Path of fileName from NSLog). 我正在iOS模拟器中运行代码,并希望将文件写入以下位置:/ Users / user / Library / Developer / CoreSimulator / Devices / 85DDC17D-A771-40D9-99BE-71FF6B60D2DF / data / Containers / Data /Application/BD30A945-25DB-4ECE-B7F7-E9C20C6691C7/Documents/textfile.txt(来自NSLog的fileName路径)。
As @rckoenes pointed out it was an error in the rest of my code. 正如@rckoenes指出的那样,这是我其余代码中的错误。 I have a function that deletes all files in "documents", i just didn't remember that i had this function and because of the length of the code (>5000 lines) it was hard to find. 我有一个删除“文档”中所有文件的功能,只是我不记得我有这个功能,而且由于代码的长度(> 5000行),很难找到它。 Thank you all! 谢谢你们!
working with URLs is a bit reliable way, so I would re-work your idea slightly like eg this: 使用URL是一种可靠的方式,因此我将稍微修改一下您的想法,例如:
NSURL *_documentFolder = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *_fileURL = [_documentFolder URLByAppendingPathComponent:@"textFile.txt"];
NSError *_error = nil;
BOOL _success = [@"hello!" writeToURL:_fileURL atomically:TRUE encoding:NSUTF8StringEncoding error:&_error];
that works perfectly on simulator and on real device too, and the file textFile.txt
will have the content hello!
可以在模拟器和真实设备上完美运行,并且文件textFile.txt
将具有内容hello!
. 。
NOTE: if the _success
value is FALSE
, you can get more information about the reason via a the _error
, even if you'd just log it to the debug-console. 注意:如果_success
值为FALSE
,即使您只是将其记录到调试控制台,也可以通过_error
获得有关原因的更多信息。 I have not isolated the NSString
in my example, but you can replace it with your own instance. 我没有在示例中隔离NSString
,但是您可以将其替换为自己的实例。
please check below code: 请检查以下代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:@"textfile.txt"];
NSString *temp = [[NSString alloc] initWithString:@"Test Content"];
[temp writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.