Remove non-character characters from NSString in objective-c

I have an application that synchronizes data with a remote database that users fill out. It seems that people copy and paste shit from tons of different OS and programs, which can lead to the introduction of various hidden values ​​not ASCII into the system.

For example, I get the following:

Artist:Γ’ Γ’ Ioco 

This leads to being sent back to the system during synchronization, and my JSON conversion alleviates the problem, and invalid characters in different places cause my application to crash.

How do I search and clear any of these invalid characters?

+4
source share
1 answer

Although I strongly believe that unicode support is the right way, here is an example of how you can limit a string to only certain characters (in this case ASCII):

 NSString *test = @"OlΓ©, seΓ±or!"; NSMutableString *asciiCharacters = [NSMutableString string]; for (NSInteger i = 32; i < 127; i++) { [asciiCharacters appendFormat:@"%c", i]; } NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet]; test = [[test componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString:@""]; NSLog(@"%@", test); // Prints @"Ol, seor!" 
+20
source

All Articles