How to make an NSString path (file name) safe

后端 未结 7 721
陌清茗
陌清茗 2021-02-01 01:52

I\'m using very tricky fighting methods :) to make a string like Fi?le*/ Name safe for using as a file name like File_Name. I\'m sure there is a cocoa

7条回答
  •  一向
    一向 (楼主)
    2021-02-01 02:12

    This will remove all invalid characters anywhere in the filename based on Ismail's invalid character set (I have not verified how complete his set is).

    - (NSString *)_sanitizeFileNameString:(NSString *)fileName {
        NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"/\\?%*|\"<>"];
        return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""];
    }
    

    Credit goes to Peter N Lewis for the idea to use componentsSeparatedByCharactersInSet:
    NSString - Convert to pure alphabet only (i.e. remove accents+punctuation)

提交回复
热议问题