【发布时间】:2014-11-26 16:24:27
【问题描述】:
(我的母语不是英语。抱歉我的英语不好......)
我之前用这段代码成功写过文件。
// worked code...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"myfile.txt"];
NSString *myStr = @"this is a string";
if( ! [myStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL] )
return FALSE;
else
return TRUE;
现在我想用NSFileManager 更改此代码。
所以,我就这样尝试了。
// not worked code...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"myfile.txt"];
NSString *myStr = @"this is a string";
NSData *fileData = [myStr dataUsingEncoding: NSUTF8StringEncoding];
NSFileManager *fm;
if( [fm createFileAtPath: filePath contents: fileData attributes: nil] == NO )
return FALSE;
else
return TRUE;
每当我构建此代码时,它都会返回为 false... 难道我做错了什么??请帮帮我
【问题讨论】:
-
您能记录下
filePath的值吗?通常使用– stringByAppendingString:将路径组件 添加到当前URL 是一种不好的做法。 -
感谢您的评论。这是我的道路。
/Users/[myUserName]/Library/Application Support/iPhone Simulator/7.0.3/Applications/08F89652-CA57-4136-9889-46458D00AC9A/Documentsmyfile.txt并且在使用stringByAppendingString之后,它变成了Documents/myfile.txt。但是,即使我检查了文件是否存在,它仍然无法写入。 -
我解决了这个问题。谢谢
标签: ios objective-c file-io nsdata nsfilemanager