【问题标题】:Renaming an existing file with Obj-C使用 Obj-C 重命名现有文件
【发布时间】:2013-01-11 15:12:39
【问题描述】:

我已经看到这个问题被问了几次,但到目前为止我无法使用任何帖子解决方案取得成功。我想要做的是重命名应用程序本地存储中的文件(对于 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]];
}

【问题讨论】:

  • 所以您想将Documents 目录中的newPDF.pdf 重命名为传递给该方法的任何内容?
  • 正确!想要做到这一点。
  • xcode 只是一个 IDE。我实际上被标题和标签激怒了,起初我以为你想重命名/重构方法名称 setPDFName。

标签: objective-c


【解决方案1】:
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];

【讨论】:

    【解决方案2】:

    代码很乱;试试这个:

    - (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: 方法放入一个实用程序类中并使其成为一个类方法,以便可以从项目中的任何位置调用它。

    【讨论】:

    • 为什么建议不好?这也不适合一个类别,因为它假定要重命名的文件位于 Documents 目录中,这对于一个类别来说是违​​反直觉的,并且更适合项目范围内的一个类。
    • 实际上这包含了很好的建议:stringByAppendingPathComponent 比使用stringWithFormat 构建路径更好。
    • 我猜是这样 ^^ 它从来都不是个人的,但是是的......你是对的......但在这里它不是,我确实写了:) 开始困扰着我! [无论如何,我不会拒绝投票]
    • 一切都困扰着你。只要调用者理解,线程安全就没有问题。我的大多数方法都忽略了线程安全,因为在我明确执行多线程之前它基本上不是问题。
    • 实际上我在这里看不到任何线程问题。来自文档:“可以从多个线程安全地调用共享 NSFileManager 对象的方法。”只要不使用文件管理器delegate进行回调,应该没有问题。
    猜你喜欢
    • 2014-03-27
    • 2021-11-16
    • 2023-03-21
    • 2018-07-23
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多