I've seen this question asked a few times but I have been unable thus far to achieve success using any of the post solutions. What I am trying to do is rename a file in the local storage of an app (also kind of new to Obj-c). I am able to retrieve the old path and create the new path, but what would I have to write in order to actually change the files name?
What I have thus far is:
- (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]];
}
Open File Explorer by going to My Computer, or by pressing Windows Key + E on your keyboard. Find the file you want to rename, select it and select Rename on the ribbon (or press F2 on your keyboard). Type the new name you want the file to have and press Enter.
You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.
If you want to rename a file name containing spaces to a new file name with spaces, place quotation marks around both file names, as in the following example. The same examples above can be applied to the copy, rename, delete, or other commands in the Windows command line that involve a file name with a space.
Select the project you want to rename in the “Project Navigator” which can be found on the left side of the Xcode view. On the right-hand side of the window, select the “File Inspector”. The name of your project should be in there under “Identity and Type”, change it to “NEW” and press Enter.
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
The code is very messy; try this:
- (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 call this using:
if (![self renameFileFrom:@"oldName.pdf" to:@"newName.pdf])
{
// Something went wrong
}
Better still, put the renameFileFrom:to:
method into a utility class and make it a class method so it can be called from anywhere in your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With