从NSString创建一个安全的文件名?

Cam*_*oft 6 iphone nsstring ios4 ios

有没有办法获取NSString并将其转换为安全版本,可以用作文件名保存到iPhone上的用户文档目录.

我现在正在做这样的事情:

NSString *inputString = @"This is sample text which may have funny chars and spaces in.";

NSInteger len = [inputString length];        
NSString *newFilename = [[inputString substringToIndex:MIN(20, len)] stringByAppendingPathExtension:@"txt"];
Run Code Online (Sandbox Code Playgroud)

这目前让我有类似的东西:

This is sample text .txt
Run Code Online (Sandbox Code Playgroud)

需要确保文件名中不允许使用的字符并将其删除.

els*_*ooo 5

你最终可能会得到一些正则表达式.仅仅因为使用except-filter 太危险了(你可能会错过一些非法的字符).

因此我建议您使用RegexKitLite(http://regexkit.sourceforge.net/RegexKitLite/),并结合以下代码行:

inputString = [inputString stringByReplacingOccurencesOfRegex:@"([^A-Za-z0-9]*)" withString:@""];
Run Code Online (Sandbox Code Playgroud)

这将替换除AZ,az和0-9 =)之外的所有字符!