2010-12-20 19 views

Respuesta

7
NSString *oldDirectoryPath = @"Type your old directory Path"; 

NSArray *tempArrayForContentsOfDirectory =[[NSFileManager defaultManager] contentsOfDirectoryAtPath:oldDirectoryPath error:nil]; 

NSString *newDirectoryPath = [[oldDirectoryPath stringByDeletingLastPathComponent]stringByAppendingPathComponent:newDirectoryname]; 

[[NSFileManager defaultManager] createDirectoryAtPath:newDirectoryPath attributes:nil]; 

for (int i = 0; i < [tempArrayForContentsOfDirectory count]; i++) 
{ 

NSString *newFilePath = [newDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]]; 

NSString *oldFilePath = [oldDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]]; 

NSError *error = nil; 
[[NSFileManager defaultManager] moveItemAtPath:oldFilePath toPath:newFilePath error:&error]; 

if (error) { 
// handle error 
} 

} 
+0

Disculpa si me perdí algo en alguna parte, pero ¿no es necesario que elimines el directorio anterior también? –

+0

@ Peter Johnson: si no necesita eliminar su directorio anterior, puede usar el mismo código reemplazando la línea: [[NSFileManager defaultManager] moveItemAtPath: oldFilePath toPath: newFilePath error: & error]; a [[NSFileManager defaultManager] copyItemAtPath: oldFilePath toPath: newFilePath error: & error] ;. – iPhoneDv

+1

la respuesta sugerida por mackross es mucho más directa y menos intrincada. –

15

¿Has probado?

NString *newDirectoryName = @"<new folder name>";  
    NSString *oldPath = @"<path to the old folder>"; 
    NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName]; 
    NSError *error = nil; 
    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error]; 
    if (error) { 
     NSLog(@"%@",error.localizedDescription); 
     // handle error 
    } 
+0

he probado este already..it no está funcionando .. – iPhoneDev

+0

¿Cómo le va el camino? – mackross

+0

también recibe un mensaje de error? NSLog (@ "% @", error.localizedDescription); – mackross

1

Esto siempre funciona

NSLog (@"Copying download file from %@ to %@", aPath, bPath); 
if ([[NSFileManager defaultManager] fileExistsAtPath: bPath]) { 
      [[NSFileManager defaultManager] removeItemAtPath: bPath 
                 error: &error]; 
     } 

if (![[NSFileManager defaultManager] copyItemAtPath: aPath 
                toPath: bPath 
                 error: &error]){} 
if ([[NSFileManager defaultManager] removeItemAtPath: aPath 
                 error: &error]) {} 
+0

Éste tiene un efecto secundario de duplicar los datos. En caso de que los datos sean grandes, o si la aplicación falla en el medio de la operación, esto podría causar un problema. –

5

Usando moveItemAtPath debería funcionar. En ocasiones, el directorio no se renombra en realidad, sino que se traslada a otro lugar. En este caso, también se debe crear la estructura de directorio de la ruta de destino. Aquí un fragmento de código que estoy usando que funciona bien:

-(BOOL)renameDir:(NSString *)dirPath asDir:(NSString *)newDirPath cleanExisting:(BOOL)clean 
{ 
    NSError *error = nil; 
    NSFileManager *fm = [NSFileManager defaultManager]; 
    if (clean && [fm fileExistsAtPath:newDirPath]) 
    { 
     [fm removeItemAtPath:newDirPath error:&error]; 
     if (error != nil) 
     { 
      NSLog(@"Error while renameDir %@ as %@ :\n%@",dirPath,newDirPath,error); 
      return NO; 
     } 
    } 
    //Make sure container directories exist 
    NSString *newDirContainer = [newDirPath stringByDeletingLastPathComponent]; 
    if (![fm fileExistsAtPath:newDirContainer]) 
    { 
     [fm createDirectoryAtPath:newDirContainer withIntermediateDirectories:YES attributes:nil error:&error]; 
    } 

    if (error==nil) 
    { 
     [fm moveItemAtPath:dirPath toPath:newDirPath error:&error]; 
    } 
    if (error!=nil) 
    { 
     NSLog(@"error while moveItemAtPath : %@",error); 
    } 
    return (error==nil); 
} 
+0

No limpia el directorio anterior ... ¿lo hace? –

0

Esto es bueno artículo para renombrar, borrar y crear archivos.

// For error information 
    NSError *error; 

// Create file manager 
    NSFileManager *fileMgr = [NSFileManager defaultManager]; 

// Point to Document directory 
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 
// Rename the file, by moving the file 
    NSString *filePath2 = [documentsDirectory stringByAppendingPathComponent:@"file2.txt"]; 

// Attempt the move 
    if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES) 
     NSLog(@"Unable to move file: %@", [error localizedDescription]); 

// Show contents of Documents directory 
    NSLog(@"Documents directory: %@", 
    [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]); 

http://iosdevelopertips.com/data-file-management/iphone-file-system-creating-renaming-and-deleting-files.html

Cuestiones relacionadas