2010-08-17 46 views
36

Tôi có một tệp có tên a.caf trong thư mục tài liệu. Tôi muốn đổi tên nó khi người dùng nhập vào số UITextField và nhấn thay đổi (văn bản được nhập trong số UITextField phải là tên tệp mới).Cách đổi tên tệp bằng NSFileManager

Tôi làm cách nào để thực hiện việc này?

+1

Câu hỏi này sẽ trả lời bạn: http://stackoverflow.com/questions/873522/rename-file-in-cocoa –

Trả lời

82

Bạn có thể sử dụng 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]; 
13

Để giữ cho câu hỏi này to-date up-, tôi thêm phiên bản Swift cũng như:

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) 
} 
+0

này không làm việc trong nhanh chóng 3,0 –

+0

tôi đã không giữ nó up-to- ngày. Cảm ơn những người đứng đầu, tôi sẽ cập nhật câu trả lời. – Michal

+2

Bạn đang thiếu 'let manager = NSFileManager()' – boidkan

0

Làm việc trên Swift 2,2

func moveFile(pre: String, move: String) -> Bool { 
    do { 
     try NSFileManager.defaultManager().moveItemAtPath(pre, toPath: move) 
     return true 
    } catch { 
     return false 
    } 
} 
2

Đây là chức năng của daehan park để chuyển đổi sang Swift 3:

func moveFile(pre: String, move: String) -> Bool { 
    do { 
     try FileManager.default.moveItem(atPath: pre, toPath: move) 
     return true 
    } catch { 
     return false 
    } 
} 
Các vấn đề liên quan