Search code examples
iosobjective-cfile-ionsdatansfilemanager

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


Solution

  • 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.