7

この質問が何度か聞かれるのを見てきましたが、これまでのところ、投稿ソリューションを使用して成功を収めることができませんでした. 私がやろうとしているのは、アプリのローカル ストレージにあるファイルの名前を変更することです (これも 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]];
}
4

2 に答える 2

19
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
于 2013-01-11T15:15:27.660 に答える
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:メソッドをユーティリティ クラスに入れ、それをクラス メソッドにして、プロジェクトのどこからでも呼び出せるようにすることです。

于 2013-01-11T15:22:05.183 に答える