Renaming an existing file with Obj-C

前端 未结 2 1774
无人及你
无人及你 2021-01-12 08:26

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

相关标签:
2条回答
  • 2021-01-12 09:18

    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.

    0 讨论(0)
  • 2021-01-12 09:21
    NSError *error = nil;
    [[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
    
    0 讨论(0)
提交回复
热议问题