2010-08-17 6 views
36

J'ai un seul fichier nommé a.caf dans le répertoire de documents. Je voudrais le renommer lorsque l'utilisateur tape dans un UITextField et appuie sur le changement (le texte entré dans le UITextField devrait être le nouveau nom de fichier).Comment renommer un fichier en utilisant NSFileManager

Comment est-ce que je peux faire ceci?

+1

Cette question répondra à la vôtre: http://stackoverflow.com/questions/873522/rename-file-in-cocoa –

Répondre

82

Vous pouvez utiliser 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

Pour garder cette question mise à jour, j'ajoute la Swift la version ainsi:

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

cela ne fonctionne pas rapide 3.0 –

+0

Je ne l'ai pas gardé jusqu'à-to rendez-vous amoureux. Merci pour les heads up, je vais mettre à jour la réponse. – Michal

+2

Il vous manque 'let manager = NSFileManager()' – boidkan

0

sur Swift A travaillé 2,2

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

Ceci est la fonction par Daehan Park pour convertir en Swift 3:

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