decomposedStringWithCanonicalMapping
Returns a string made by normalizing the receiver’s contents using Form D.
- (NSString *)decomposedStringWithCanonicalMapping
Return Value
A string made by normalizing the receiver’s contents using the Unicode Normalization Form D.
Example of [NSString decomposedStringWithCanonicalMapping]
NSString *eachCellContent = @"소";
NSString *searchText = @"ㅅ";
NSString *normalizedContent = [eachCellContent decomposedStringWithCanonicalMapping];
NSString *normalizedSearch = [searchText decomposedStringWithCanonicalMapping];
NSComparisonResult result = [normalizedContent compare:normalizedSearch
options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch
range:NSMakeRange(0, [normalizedSearch length])
locale:[NSLocale currentLocale]];
if (result == NSOrderedSame) {
NSLog(@"same");
}
// Output: same
Example of [NSString decomposedStringWithCanonicalMapping]
NSArray *array = [NSArray arrayWithObjects:@"éli", @"bob", @"earl", @"allen", @"àli", nil];
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSString*)obj1 compare:obj2 options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
}];
NSMutableDictionary *sectioned = [NSMutableDictionary dictionary];
NSString *firstChar = nil;
for(NSString *str in sorted)
{
//Ignore empty strings
if(![str length])continue;
NSMutableArray *names = nil;
//Compare the first character using diacritic insensitive search
if([str compare:firstChar options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch range:NSMakeRange(0, 1)] == NSOrderedSame)
{
names = [sectioned objectForKey:firstChar];
}
else
{
//decomposedStringWithCanonicalMapping is where the magic happens
//(it removes the accent mark)
firstChar = [[str decomposedStringWithCanonicalMapping] substringToIndex:1];
names = [NSMutableArray array];
[sectioned setObject:names forKey:firstChar];
}
[names addObject:str];
}
NSLog(@"sorted: %@", sorted);
//This is sectioned like the address app
NSLog(@"sectioned: %@", sectioned);
Example of [NSString decomposedStringWithCanonicalMapping]
- (NSString*) decomposeAndFilterString: (NSString*) string
{
NSMutableString *decomposedString = [[string decomposedStringWithCanonicalMapping] mutableCopy];
NSCharacterSet *nonBaseSet = [NSCharacterSet nonBaseCharacterSet];
NSRange range = NSMakeRange([decomposedString length], 0);
while (range.location > 0) {
range = [decomposedString rangeOfCharacterFromSet:nonBaseSet
options:NSBackwardsSearch range:NSMakeRange(0, range.location)];
if (range.length == 0) {
break;
}
[decomposedString deleteCharactersInRange:range];
}
return [decomposedString autorelease];
}