cocoa - 将文件名与文件扩展名 Cocoa 分开?

标签 cocoa filenames nsbundle writetofile

我正在使用 writeToFile:atomically: 方法将一些加密数据写入文本文件。问题是,需要保存的文件必须是用户加密的文件,并带有我选择的扩展名。这是我到目前为止所拥有的:

[encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] 
    stringByAppendingPathComponent:@"encryptedfile.txt.kry"] atomically:YES];
                                           ^//fileName here

如您所见,加密的文件名被硬编码为 cryptofile.txt.kry。但假设用户选择文件“test.avi”进行加密,则写入桌面的加密文件应命名为test.avi.kry。所以应该有ofType:,就像NSBundle中一样。我知道这里有一些 NSString 方法可以使用,但已经忘记了。

谢谢!

最佳答案

不能将 .kry 附加到文件名上吗?

如果您有路径,并且只需要文件名,则可以使用 - (NSString *)lastPathComponent:

NSString *filename = [filePath lastPathComponent];
[encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] 
    stringByAppendingPathComponent:[filename stringByAppendingString:@".kry"] atomically:YES];

如果您想要不带扩展名的文件名,可以使用- (NSString *)stringByDeletingPathExtension:

NSString *filename = [[filePath lastPathComponent] stringByDeletingPathExtension];

关于cocoa - 将文件名与文件扩展名 Cocoa 分开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7297403/

相关文章:

cocoa - NSTableColumn 绑定(bind)到 BOOL 值

windows - 如何在 Windows 中解析规范文件名?

ios - 为什么我的应用程序包没有创建文件夹?

cocoa - Xcode : Garbage Collector Setting

objective-c - 椭圆形 NSTextField?

bash - 如何在 bash 脚本中使用包含带空格的文件名的变量?

http - 将 CGI 脚本的输出保存在与脚本名称不同的文件名下

ios - 将所有捆绑资源复制到 Documents 目录内的单独文件夹中

objective-c - 使用 [NSBundle loadNibNamed :owner:] but the window does not appear in the foreground 加载 NIB

ios - 我应该在 iOS/OS X 应用程序中的哪里初始化我的单例?