如何使用NSFileManager重命名文件

Dip*_*mar 37 nsfilemanager

我在文档目录中有一个名为a.caf的文件.当用户键入a UITextField并按下更改时,我想重命名它(输入的文本UITextField应该是新文件名).

我怎样才能做到这一点?

dic*_*ciu 83

您可以使用moveItemAtPath.

NSError * err = NULL;
NSFileManager * fm = [[NSFileManager alloc] init];
BOOL result = [fm moveItemAtPath:@"/tmp/test.tt" toPath:@"/tmp/dstpath.tt" error:&err];
if(!result)
    NSLog(@"Error: %@", err);
[fm release];
Run Code Online (Sandbox Code Playgroud)


Mic*_*hal 13

为了使这个问题保持最新,我还添加了Swift版本:

let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let originPath = documentDirectory.stringByAppendingPathComponent("/tmp/a.caf")
let destinationPath = documentDirectory.stringByAppendingPathComponent("/tmp/xyz.caf")

var moveError: NSError?
if !manager.moveItemAtPath(originPath, toPath: destinationPath, error: &moveError) {
    println(moveError!.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)

  • 你缺少`let manager = NSFileManager()` (2认同)

小智 5

这是 daehan park 转换为 Swift 3 的函数:

func moveFile(pre: String, move: String) -> Bool {
    do {
        try FileManager.default.moveItem(atPath: pre, toPath: move)
        return true
    } catch {
        return false
    }
}
Run Code Online (Sandbox Code Playgroud)