使用Obj-C重命名现有文件

Cha*_*llo 7 objective-c

我已经看过几次这个问题,但到目前为止我还没有能够使用任何后期解决方案取得成功.我想要做的是重命名应用程序的本地存储中的文件(也是Obj-c的新类型).我能够检索旧路径并创建新路径,但为了实际更改文件名,我必须编写什么?

我到目前为止:

- (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]];
}
Run Code Online (Sandbox Code Playgroud)

Cub*_*ber 18

NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
Run Code Online (Sandbox Code Playgroud)


tro*_*foe 12

代码非常混乱; 试试这个:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

并使用以下方法调用:

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

更好的是,将renameFileFrom:to:方法放入实用程序类并使其成为类方法,以便可以从项目的任何位置调用它.