简体   繁体   English

在iOS中使用NSFileManager写入文件

[英]Writing file with NSFileManager in iOS

(I'm not native English speaker. Sorry about my bad English...) (我不是英语母语人士。抱歉我的英语不好...)

I succeed to write file before with this code. 我使用此代码成功写入了文件。

// 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;

And now I want to change this code with NSFileManager . 现在,我想使用NSFileManager更改此代码。 So, I tried just like this. 所以,我尝试了这样。

// 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;

Everytime when I build this code, it keeps returned as false... Am I doing something wrong?? 每当我构建此代码时,它都会一直返回为false ...我做错了吗? Please help me 请帮我

The difference is basically the NSFileManager method won't overwrite an existing file where as the NSString method will : 区别基本上是NSFileManager方法不会覆盖现有文件,因为NSString方法

From the NSFileManager reference : NSFileManager 参考

Return Value 返回值

YES if the operation was successful or if the item already exists, otherwise NO . YES如果操作成功,或者如果该项目已经存在,否则NO

From the NSString reference : NSString 参考

Discussion 讨论区

This method overwrites any existing file at path. 此方法将覆盖路径上的所有现有文件。

If you always want to write a fresh copy of the data, then check if the file exists first and delete it if it does. 如果您始终要写入数据的新副本,请先检查文件是否存在,然后删除该文件。

ALSO : You should not be using [NSString stringByAppendingString:] to construct the filepath; :您不应该使用[NSString stringByAppendingString:]构造文件路径; instead use [NSString stringByAppendingPathComponent:] ; 而是使用[NSString stringByAppendingPathComponent:] ; I expect you aren't even writing the file you think you are, because of this. 因此,我希望您甚至都不会写出您认为是的文件。

Better still, use NSURL to refer to files; 更好的是,使用NSURL来引用文件; which is the preferred method. 这是首选方法。

Your NSFileManager is not set to any file manager. 您的NSFileManager尚未设置为任何文件管理器。

Instead you should try to initialise it with the defaultManager with the following code. 相反,您应该尝试使用带有以下代码的defaultManager对其进行初始化。

NSFileManager *fm = [NSFileManager defaultManager]; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM