按第二个字sortingnsarray。 (按“姓氏姓氏”种string排列)

我有像“fistname surname”string的nsarray。 现在我想按字sortingstring数组,即通过姓氏。 我用这个方法

NSArray *sortedArray=[[teachersList allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSLog(@"After %@",sortedArray); 

但它sorting在第一个字。

而且我也有元素或stringfirstname只意味着第一个字。

那么如何做到这一点?

编辑

@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]:发送给实例的无法识别的select器

你可以做类似的,

 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 //ie 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]将直接保存string值,所以您应该如下所示

 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]; }]; 

上面的代码将直接以sorting的方式为您提供所有值的数组。

因为你有单一的string,它会一直开始比较“ first name

所以你必须首先空间分割string

 NSArray *listItems = [list componentsSeparatedByString:@" "]; 

从这里你必须build立一个这样的分割string的名称字典

 @{@"FirstName" : listItems[0], "FirstName" : listItems[1]} 

add into array and then you can sort对此add into array and then you can sort

 NSArray *keys = [theDictionary allKeys]; NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];