我正在使用像“姓氏姓氏”这样的字符串。现在我想用第二个词,即姓氏来排序那个字符串数组。 我用过这个方法
NSArray *sortedArray=[[teachersList allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"After %@",sortedArray);
但它在第一个单词上排序数组。
我也有字符的元素或字符串只表示第一个单词。
那怎么办呢?
修改
@Janak Nirmal
我的修改后的代码是:
while([resultSet next])
{
[teachersList setObject:[NSString stringWithFormat:@"%@ %@",[resultSet stringForColumn:@"first_name"],[resultSet stringForColumn:@"last_name"]] forKey:[resultSet stringForColumn:@"email_id"]];
[emailList addObject:[resultSet stringForColumn:@"email_id"]];
appDelegate.grade=[resultSet stringForColumn:@"grade"];
}
//NSArray *sortedArrays=[[teachersList allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSArray *sortedArray = [[teachersList allValues] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *firstTeacher2ndWord = [[[[(Teacher*)a name] componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
NSString *secondTeacher2ndWord = [[[[(Teacher*)b name] componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
return [firstTeacher2ndWord compare:secondTeacher2ndWord];
}];
但我收到了以下错误
[__ NSCFString name]:发送到实例的无法识别的选择器
答案 0 :(得分:4)
你可以这样做,
NSArray *sortedArray = [teacherList sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *firstTeacher2ndWord = [[[[(Teacher*)a name] componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
NSString *secondTeacher2ndWord = [[[[(Teacher*)b name] componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
return [firstTeacher2ndWord compare:secondTeacher2ndWord];
}];
//Assuming in above you have atleast 2 words in name
//i.e. objectAtIndex:1 doesn't fail or you need to put condition
//there according to your needs
假设您的模型结构如下,
@interface Teacher : NSObject
@property (nonatomic,strong) NSString *name;
@end
修改强>
由于您的[teacherList allValues]将直接保存字符串值,您应该按如下所示编写
NSArray *sortedArray = [[teachersList allValues] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *firstTeacher2ndWord = [[[((NSString*)a) componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
NSString *secondTeacher2ndWord = [[[((NSString*)b) componentsSeparatedByString:@" "] objectAtIndex:1] lowercaseString];
return [firstTeacher2ndWord compare:secondTeacher2ndWord];
}];
上面的代码将直接以排序的方式为您提供所有值的数组。
答案 1 :(得分:2)
因为您有单个字符串,它将始终从“first name
”
所以你必须先按空格分割字符串
NSArray *listItems = [list componentsSeparatedByString:@" "];
从这里开始,您必须使用此分割字符串(如
)构建名称字典@{@"FirstName" : listItems[0], "FirstName" : listItems[1]}
和add into array and then you can sort
这个
NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];