在Objective-C中对自定义对象的数组进行排序

时间:2017-02-14 06:43:21

标签: objective-c sorting nsstring nsarray

我有两个班级,ViewControllerBViewControllerBViewController类具有属性名称,地址和评级。

以下是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;
     }

2 个答案:

答案 0 :(得分:1)

你的数组

NSMutableArray *arrMain = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil];

现在根据评级键进行排序

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

<强>测试

希望,它会帮助你。
感谢

答案 1 :(得分:1)

Apple有一个API可以以优雅的方式做你想做的事情:

NSMutableArray *yourArray = [NSMutableArray arrayWithObjects:b, c, d, e ,f, nil];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rating" ascending:YES];
[yourArray sortUsingDescriptors:@[sortDescriptor]];

你的数组现在已经很好地排序了。