ios文件写入不工作
我想写一个简单的数据文件,它不工作ios文件写入不工作,ios,objective-c,nsfilemanager,Ios,Objective C,Nsfilemanager,我想写一个简单的数据文件,它不工作 - (void)writeStringToFile:(NSString*)aString { // Build the path, and create if needed. NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString* f
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
NSLog(@"%@",fileAtPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
}
您仍然可以修改应用程序的文档目录 检查路径中是否存在文件
NSFileManager *fileManager = [NSFileManager defaultManager];
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
NSLog(@"File exists");
}
检查是否可写、可读和可执行
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
NSLog(@"isWritable");
}
if ([fileManager isReadableFileAtPath:@"FilePath"]) {
NSLog(@"isReadable");
}
if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
NSLog(@"is Executable");
}
试试这个
快乐编码(^ ^)像这样试试
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = @"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
NSLog(@"%@",fileAtPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
// The main act...
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:YES];
}}
你怎么知道它不工作?你的代码看起来不错,但是没有错误报告。使用
[NSData writeToFile:options:error://code>并检查返回代码并记录错误对象。为什么要使用if
语句以及为什么要调用createFileAtPath
?你也不需要。只需调用writeToFile:options:error:
。hi未找到任何文件名bookmark.json,因此如果文件存在,它不会写入字符串?而且它不会检测和报告错误。更糟糕的是OPs代码。可以使用[NSData writeToFile:options:error:]代替。。。!是的,我知道。然而,我对您的代码实际演示的内容进行了评论。