问题
I may be looking at this incorrectly, but right now, if a user enters certain special characters in a search bar, the app will crash. These include \ and '.
The apostrophe is a problem, in that words like "isn't" and "doesn't" will cause a crash
How should I go about working around this problem?
Many thanks
回答1:
Before doing a search using the search string, pre-filter it, like this:
NSString *safeSearchString = [[searchString componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]] componentsJoinedByString:@""];
回答2:
Why don't you escape the characters and actually search for what the user wants instead of ignoring or removing what they want ?
Are you using SQLite ? If so then you can escape a single quote by another single quote.
回答3:
The UISearchBar utilizes the UISearchBarDelegate protocol. To stop users entering \ and ' all you need to do is to override the searchBar:shouldChangeTextInRange:replacementText: method and if you sense the special characters in the text, you simply return NO.
But handling (rather than ignoring) these special chars in your program is a better user experience. After all why are you users even searching for "isn't" and "doesn't" in the first place?
来源:https://stackoverflow.com/questions/9241139/ios-how-to-avoid-special-characters-being-entered-in-a-search-bar