我有两个类,即ViewController
和BViewController
。BViewController
类具有属性名称,地址和等级。
下面是ViewController.m
的代码
我如何排列数组中的对象,以使它们按等级升序排序?此外,如何在视图中显示它们?
- (void)viewDidLoad {
[super viewDidLoad];
BViewController *b=[[BViewController alloc]init];
b.name=@"x";
b.address=@"bangalore";
b.rating=@6;
BViewController *c=[[BViewController alloc]init];
c.name=@"y";
c.address=@"bangalore";
c.rating=@5;
BViewController *d=[[BViewController alloc]init];
d.name=@"z";
d.address=@"bangalore";
d.rating=@7;
BViewController *e=[[BViewController alloc]init];
e.name=@"abc";
e.address=@"bangalore";
e.rating=@4;
BViewController *f=[[BViewController alloc]init];
f.name=@"xyz";
f.address=@"bangalore";
f.rating=@8;
}
Apple有一个API可以优雅地完成您想做的事情:
NSMutableArray *yourArray = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rating" ascending:YES];
[yourArray sortUsingDescriptors:@[sortDescriptor]];
您的数组现在已经很好地排序了。
您的数组
NSMutableArray *arrMain = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil];
现在基于rating键进行排序
NSArray *arrResult;
arrResult = [arrMain sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSNumber *first = [(BViewController*)a rating];
NSNumber *second = [(BViewController*)b rating];
NSComparisonResult result = [first compare:second];
return result;
}];
已测试。