gpt4 book ai didi

ios - 使用不同的类和键对数组进行排序

转载 作者:行者123 更新时间:2023-12-01 19:07:23 26 4
gpt4 key购买 nike

我想使用不同的描述符键对对象进行排序。

问题:

我有两个数组,其中填充了不同类的对象。和这两个类不共享用作排序描述符的 public 属性。

我想按字母顺序对数组进行排序,并且仅返回一个包含所有对象的数组。

  • Array1 =带有对象[A类]
  • 按“名称”排序
  • Array2 =带有对象[B类]
  • 按“标题”排序

  • FinalArray =>使用数组的所有对象(1,2)按字母顺序(再次)排序

    最佳答案

    您可以这样做:

  • 使用组合数组
  • 的大小创建 NSArray *result
  • 通过将第一个数组的元素然后将第二个数组的元素复制到result中,将两个数组合并为result数组。
  • sortedArrayUsingComparator:与“理解”两种类型的比较器一起使用。

  • 这是一个基本的实现:
    NSArray *sortedArray = [result sortedArrayUsingComparator: ^(id obj1, id obj2) {
    NSString *key1, *key2;
    if ([obj1 isKindOfClass:['class has a title' class]]) {
    key1 = [obj1 title];
    } else { // It's the kind of objects that has a name
    key1 = [obj1 name];
    }
    if ([obj2 isKindOfClass:['class has a title' class]]) {
    key2 = [obj2 title];
    } else { // It's the kind of objects that has a name
    key2 = [obj2 name];
    }
    // Do the comparison
    return [key1 caseInsensitiveCompare:key2];
    }];

    关于ios - 使用不同的类和键对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18832985/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com