In tableview, index is used to process English characters, Chinese characters (narrow characters and wide characters), and tableview is used to process English characters.
[Problem description]
I encountered a tableview index problem when developing the iOS Address Book Project.
The test student found A bug: adding A section named "wide character A" cannot be merged into index A. Instead, an index named "A" is added,
Medium: An exception occurs at the end of the Right index. ABX is not merged into a normal index, but appears between Z and # Of a normal index.
[Problem Analysis]
Think about it, it should be because the encoding of the width Character A and A is inconsistent.
The previous code is like this. Check that the second line uses a regular expression to determine whether the first letter starts with a Latin letter and then mark this person as starting with a certain character. The Code is as follows:
NSPredicate * HanziPred = [NSPredicate attributes: @ "self matches % @", @ "[\ u4e00-\ u9fa5]"]; NSPredicate * EnglishPred = [NSPredicate attributes: @ "self matches % @", @ "^ [A-Z]. * $ "]; NSPredicate * numberPred = [NSPredicate predicateWithFormat: @" self matches % @ ", @" ^ [0-9]. * $ "]; if ([EnglishPred evaluateWithObject: first]) {// The Latin letter self. firstLetter = self. latinString. length> 0? [Self. latinString substringToIndex: 1]: @ "#";}
Assign the first value to firstLetter using a regular expression. Regular Expressions are really powerful and can be compatible with wide characters and narrow characters. In this way, both A and A conform to the regular expression, but they are actually two different characters.
[Solution]
My solution is to create a static global dictionary in advance and initialize it. When using regular expressions, first determine whether the dictionary can match to wide characters, if it can be forcibly replaced with a narrow character.
Static NSDictionary * widthLetter;-(id) init {self = [super init]; self. firstLetter = @ "#"; widthLetter = @ {@ "A": @ "A", @ "B": @ "B", @ "C ": @ "C", @ "D": @ "D", @ "E": @ "E", @ "F": @ "F", @ "G ": @ "G", @ "H": @ "H", @ "I": @ "I", @ "J": @ "J", @ "K ": @ "K", @ "L": @ "L", @ "M": @ "M", @ "N": @ "N", @ "O ": @ "O", @ "P": @ "P", @ "Q": @ "Q", @ "R": @ "R", @ "S ": @ "S", @ "T": @ "T", @ "U": @ "U", @ "V": @ "V", @ "W ": @ "W", @ "X": @ "X", @ "Y": @ "Y", @ "Z": @ "Z"}; return s Elf;} if ([EnglishPred evaluateWithObject: first]) {// Latin letters // compatible with wide characters if (widthLetter [first]) {self. firstLetter = self. latinString. length> 0? WidthLetter [first]: @ "#";} else {self. firstLetter = self. latinString. length> 0? First :@"#";}}
Result]
Both A and A can enter the index of,