我想按字母顺序排列对象数组,但数字应该在最后或最后。我有一个可变数组的对象(类型是People,sort是基于名称,这是人类的属性),在我的下面的代码中定义了_filteredArray
。
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [_filteredArray sortedArrayUsingDescriptors:sortDescriptors];
_filteredArray = [self createMutableArray1:sortedArray];
return [_filteredArray count];
上面的代码按字母顺序排序,但数字显示在顶部,这不是我想要的结果,想在字母表后显示在底部。请帮助我。提前谢谢。
答案 0 :(得分:1)
不知道这是完美的解决方案。但这会奏效。
- (void)sortArray {
NSMutableArray *arrayToSort = [NSMutableArray arrayWithObjects:@"asd",@"1",@"sr",@"42.0",@"bs",@"0", nil];
NSArray *sortedArray;
sortedArray = [arrayToSort sortedArrayUsingComparator:^NSComparisonResult(NSString *first, NSString *second) {
if([self isNumeric:first] && [self isNumeric:second]) {
return [first compare:second options:NSNumericSearch];
}
if ([self isNumeric:first]) {
return NSOrderedDescending;
}
if ([self isNumeric:second]) {
return NSOrderedAscending;
}
return [first compare:second options:NSCaseInsensitiveSearch];
}];
}
//Method which find whether the string is numeric or not
- (BOOL)isNumeric:(NSString *)string {
BOOL isNumeric = FALSE;
NSScanner *scanner = [NSScanner scannerWithString:string];
isNumeric = [scanner scanDouble:NULL] && [scanner isAtEnd];
return isNumeric;
}
答案 1 :(得分:1)
感谢每一位人士的贡献,我终于通过互联网获得了一些帮助,并根据自己的要求进行了更改。可以查看我的以下代码。
NSArray *sorted = [phoneContacts sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
/* NSOrderedAscending, NSOrderedSame, NSOrderedDescending */
SCPhoneContact *contact1 = (SCPhoneContact *)obj1;
SCPhoneContact *contact2 = (SCPhoneContact *)obj2;
BOOL isPunct1 = [[NSCharacterSet letterCharacterSet] characterIsMember:[(NSString*)contact1.name characterAtIndex:0]];
BOOL isPunct2 = [[NSCharacterSet letterCharacterSet] characterIsMember:[(NSString*)contact2.name characterAtIndex:0]];
if (isPunct1 && !isPunct2) {
return NSOrderedAscending;
} else if (!isPunct1 && isPunct2) {
return NSOrderedDescending;
}
return [(NSString*)contact1.name compare:contact2.name options:NSDiacriticInsensitiveSearch|NSCaseInsensitiveSearch];
}];
SCPhoneContact
我的对象和phoneContacts
是这些对象的数组。
感谢。