今天有朋友问我怎么给Model排序,我顺便写了一个,伸手党直接复制吧.
Person *per = [[Person alloc] init];
per.name = @"z";
per.age = 89;
Person *per1 = [[Person alloc] init];
per1.name = @"h";
per1.age = 18;
Person *per2 = [[Person alloc] init];
per2.name = @"l";
per2.age = 44;
NSMutableArray *array = [NSMutableArray array];
[array addObject:per];
[array addObject:per1];
[array addObject:per2];
NSArray *resultArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Person *per1 = obj1;
Person *per2 = obj2;
if (per1.age > per2.age) {
return NSOrderedDescending;//降序
}else if (per1.age < per2.age)
{
return NSOrderedAscending;//升序
}else
{
return NSOrderedSame;//相等
}
}];
for (Person *per in resultArray) {
NSLog(@"per.age = %ld",per.age);
}
时间: 2024-09-27 07:40:04