从文件扩展名Cocoa中分离文件名?

时间:2011-09-04 04:22:16

标签: cocoa filenames nsbundle writetofile

我使用writeToFile:atomically:方法将一些加密数据写入文本文件。问题是,需要保存的文件必须是用户加密的文件,我选择的扩展名。以下是我到目前为止的情况:

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

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

谢谢!

1 个答案:

答案 0 :(得分:1)

你能不能将.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];
相关问题