【发布时间】:2011-03-30 20:26:40
【问题描述】:
我在文档目录中有一个名为 a.caf 的文件。我想在用户输入UITextField 并按下更改时重命名它(UITextField 中输入的文本应该是新的文件名)。
我该怎么做?
【问题讨论】:
标签: nsfilemanager
我在文档目录中有一个名为 a.caf 的文件。我想在用户输入UITextField 并按下更改时重命名它(UITextField 中输入的文本应该是新的文件名)。
我该怎么做?
【问题讨论】:
标签: nsfilemanager
您可以使用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];
【讨论】:
为了保持这个问题最新,我也添加了 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)
}
【讨论】:
这是 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
}
}
【讨论】:
使用 Swift 2.2
func moveFile(pre: String, move: String) -> Bool {
do {
try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move)
return true
} catch {
return false
}
}
【讨论】: