Rename an existing file with Obj-C

I have seen this question several times, but so far I have not been able to succeed using any of the post solutions. What I'm trying to do is rename the file in the local storage of the application (same as the new one for Obj-c). I can restore the old path and create a new path, but what do I need to write to actually change the file name?

What I have so far:

- (void) setPDFName:(NSString*)name{ NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* initPath = [NSString stringWithFormat:@"%@/%@",[dirPaths objectAtIndex:0], @"newPDF.pdf"]; NSString *newPath = [[NSString stringWithFormat:@"%@/%@", [initPath stringByDeletingLastPathComponent], name] stringByAppendingPathExtension:[initPath pathExtension]]; } 
+6
source share
2 answers
 NSError *error = nil; [[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error]; 
+14
source

The code is very dirty; try the following:

 - (BOOL)renameFileFrom:(NSString*)oldName to:(NSString *)newName { NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *oldPath = [documentDir stringByAppendingPathComponent:oldName]; NSString *newPath = [documentDir stringByAppendingPathComponent:newName]; NSFileManager *fileMan = [NSFileManager defaultManager]; NSError *error = nil; if (![fileMan moveItemAtPath:oldPath toPath:newPath error:&error]) { NSLog(@"Failed to move '%@' to '%@': %@", oldPath, newPath, [error localizedDescription]); return NO; } return YES; } 

and name it using:

 if (![self renameFileFrom:@"oldName.pdf" to:@"newName.pdf]) { // Something went wrong } 

Better yet, put the renameFileFrom:to: method in the utility class and make it a class method so that it can be called from anywhere in your project.

+11
source

All Articles