【问题标题】:Sorting array of custom objects in Objective-C在 Objective-C 中对自定义对象数组进行排序
【发布时间】:2017-02-14 06:43:20
【问题描述】:

我有两个班级,即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;
     }

【问题讨论】:

    标签: objective-c sorting nsstring nsarray


    【解决方案1】:

    Apple 有一个 API 可以优雅地完成您想做的事情:

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

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

    【讨论】:

      【解决方案2】:

      你的数组

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

      这是经过测试的。

      【讨论】:

      • 你能告诉我在 storyBoard 中应该使用什么,比如 textField 或 label 来显示结果,我是新的,所以我不知道它是怎么回事!
      • @taj 对于输入,使用 UITextfields。用于排序数组命中和 UILabel 的 UIButton 以显示结果值。
      • 嘿,你能告诉我如何在控制台上看到输出吗?因为如果我把 NSLog(@"%@",arrResult);我得到了一些输出,例如“”、“”、“”、“”、“” 不明白为什么这边来了
      • @taj 因为当您执行NSLog(@"%@", b) 时,您会得到这样的结果。要获得“有意义”的日志,请覆盖 BViewController-(NSString *)description 方法,例如 return [NSString stringWithFormat:@"<%@ %p> name: %@, address: %@, rating: %@", [self class], self, _name, _address, _rating];
      猜你喜欢
      • 2012-04-25
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      相关资源
      最近更新 更多