简体   繁体   中英

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 . 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?? Please help me

The difference is basically the NSFileManager method won't overwrite an existing file where as the NSString method will :

From the NSFileManager reference :

Return Value

YES if the operation was successful or if the item already exists, otherwise NO .

From the NSString reference :

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; instead use [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; which is the preferred method.

Your NSFileManager is not set to any file manager.

Instead you should try to initialise it with the defaultManager with the following code.

NSFileManager *fm = [NSFileManager defaultManager]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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