Rename file in Cocoa?

前端 未结 5 1266
再見小時候
再見小時候 2021-01-01 11:11

How would I rename a file, keeping the file in the same directory?

I have a string containing a full path to a file, and a string containing a the new filename (and

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 11:51

    NSFileManager and NSWorkspace both have file manipulation methods, but NSFileManager's - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler is probably your best bet. Use NSString's path manipulation methods to get the file and folder names right. For example,

    NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
    [[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];
    

    Both classes are explained pretty well in the docs, but leave a comment if there's anything you don't understand.

提交回复
热议问题