2010-08-17 15 views
36

tengo un solo archivo llamado a.caf en el directorio de documentos. Me gustaría cambiar el nombre cuando usuario escribe en un UITextField y prensas cambian (el texto introducido en el UITextField debe ser el nuevo nombre de archivo).cómo cambiar el nombre de un archivo usando NSFileManager

¿Cómo puedo hacer esto?

+1

Esta pregunta contestará a la suya: http://stackoverflow.com/questions/873522/rename-file-in-cocoa –

Respuesta

82

Puede utilizar 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

Para mantener esta pregunta -actualizada, estoy añadiendo la versión Swift así:

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

esto no funciona en Swift 3.0 –

+0

No he mantenido hasta-a- fecha. Gracias por el aviso, actualizaré la respuesta. – Michal

+2

Se ha perdido 'let manager = NSFileManager()' – boidkan

0

trabajado en Swift 2,2

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

Esta es la función del parque daehan para convertir a Swift 3:

func moveFile(pre: String, move: String) -> Bool { 
    do { 
     try FileManager.default.moveItem(atPath: pre, toPath: move) 
     return true 
    } catch { 
     return false 
    } 
} 
Cuestiones relacionadas