39

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

我怎样才能做到这一点?

4

4 回答 4

84

You can use 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];
于 2010-08-17T10:13:00.807 回答
15

为了使这个问题保持最新,我还添加了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)
}
于 2015-06-18T13:41:13.887 回答
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
    }
}
于 2017-04-16T17:03:55.527 回答
1

Swift 2.2上工作

func moveFile(pre: String, move: String) -> Bool {
    do {
        try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move)
        return true
    } catch {
        return false
    }
}
于 2016-07-17T17:32:31.277 回答