How to overwrite a file with NSFileManager when copying?

后端 未结 9 708
广开言路
广开言路 2020-12-02 14:13

I\'m using this method to copy a file:

[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];

I want to overwrite a fi

9条回答
  •  清歌不尽
    2020-12-02 14:51

    You'd want to do an atomic save in this case, which would be best achieved by using NSData or NSString's writeToFile:atomically: methods (and their variants):

    NSData *myData = ...; //fetched from somewhere
    [myData writeToFile:targetPath atomically:YES];
    

    Or for an NSString:

    NSString *myString = ...;
    NSError *err = nil;
    [myString writeToFile:targetPath atomically:YES encoding:NSUTF8StringEncoding error:&err];
    if(err != nil) {
      //we have an error.
    }
    

提交回复
热议问题