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

时间:2013-01-11 15:12:39

标签: 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]];
}

2 个答案:

答案 0 :(得分:16)

NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];

答案 1 :(得分: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;
}

并使用以下方式调用此方法:

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

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

相关问题