I am trying to sort NSArray from NSDictionaries using a comparator, but I cannot get the desired result.
The result I'm trying to achieve is that the usernames AZ must be the first in the sorted array, then the usernames starting with a digit must be the second in the sorted array, and finally the usernames starting with an underscore should be last in a sorted array. Any help really appreciated!
EDIT: it needs to be sorted so that it looks consistent throughout the NSArray, so: _Anna comes before _Bob and _11Bob gets to _12Cary, but after _09Bob
An example of the desired result I'm looking for:
(
{
username = abcd;
},
{
username = Anna;
},
{
username = 01Bob;
},
{
username = 02Tob;
},
{
username = 03ZED;
},
{
username = 04_Hob;
},
{
username = 04_sob;
},
{
username = "_anna";
},
{
username = "_bob";
},
{
username = "_boc";
},
{
username = "_bocd12";
},
{
username = "_bocd13";
}
{
username = _01Bob;
},
{
username = _02Tob;
},
)
Hope this makes sense now.
NSDictionary NSArray NSDictionaries:
NSDictionary *dictionary = @{@"users":@[@{@"username":@"191anna"},@{@"username":@"_091bob"},@{@"username":@"Bob"},@{@"username":@"charlie"}]};
:
NSArray *array = [[dictionary objectForKey:@"users"] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSString *f1 = [obj1 objectForKey:@"username"];
NSString *f2 = [obj2 objectForKey:@"username"];
NSString *s1 = [[obj1 objectForKey:@"username"]substringFromIndex:1];
NSString *s2 = [[obj2 objectForKey:@"username"]substringFromIndex:1];
if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == [s2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location)
{
return [f1 localizedCaseInsensitiveCompare:f2];
}
else if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location != [s2 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location)
{
return [f1 localizedCaseInsensitiveCompare:f2];
if ([s1 rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]].location == NSNotFound)
{
return NSOrderedDescending;
}
}
return NSOrderedAscending;
}];
( , ) NSArray:
(
{
username = "_091bob";
},
{
username = 191anna;
},
{
username = Bob;
},
{
username = charlie;
}
)