NSMutableArray 中排序
程序员文章站
2022-05-24 08:21:47
...
使用sortedArrayUsingComparator方法
使用sortedArrayUsingSelector方法
使用sortedArrayUsingDescriptors:sortDescriptors
NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){ if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) { Score *s1 = (Score*)obj1; Score *s2 = (Score*)obj2; if (s1.points > s2.points) { return (NSComparisonResult)NSOrderedAscending; } else if (s1.points < s2.points) { return (NSComparisonResult)NSOrderedDescending; } } // TODO: default is the same? return (NSComparisonResult)NSOrderedSame; }];
使用sortedArrayUsingSelector方法
- (NSComparisonResult)compare:(Person *)otherObject { return [self.birthDate compare:otherObject.birthDate]; } NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
使用sortedArrayUsingDescriptors:sortDescriptors
NSSortDescriptor *sortDescriptor; sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES] autorelease]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; NSArray *sortedArray; sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];