【问题标题】:Comparing 3 arrays of various NSObject Subclasses比较各种 NSObject 子类的 3 个数组
【发布时间】:2011-11-04 16:47:54
【问题描述】:

我有一个包含 3 个 NSArrays 的 NSDictionary,

- posts
- comments
- likes.

并且在每个数组中都有一致的 NSObject 子类:

- Post
- Comment
- Like

通常,我会将这三个数组中的所有对象放入一个数组中,并使用它们都包含的相同变量来比较它们,但在这种情况下,Posts 具有变量 dateOfUploadLike 和 @ 987654326@ 具有相同的变量,日期。

如何使用变量datedateOfUpload 比较这三个数组中的对象,以创建一个由所有对象按降序排列的大数组?

【问题讨论】:

    标签: objective-c nsarray compare nsdictionary


    【解决方案1】:

    我会让他们都实现这样的方法:

    -(NSComparsionResult) compareByDate : (NSObject *) obj;
    

    当然,您需要在每个类中以不同的方式实现这一点。 然后从所有的树数组中创建一个大数组并调用

    [myArray sortUsingSelector:@selector(compareByDate:)];
    

    【讨论】:

      【解决方案2】:

      另一种方法是将所有对象添加到一个大数组中并使用块进行排序,如下所示:

      // Create the array with all the objects
      NSMutableArray *stuff = [NSMutableArray arrayWithArray:posts.allValues];
      [stuff addObjectsFromArray:comments.allValues];
      [stuff addObjectsFromArray:likes.allValues];
      
      // Sort it by using a block
      NSArray *sortedStuff = [stuff sortedArrayUsingComparator:^(id obj1, id obj2) {
          NSDate *date1 = [obj1 respondsToSelector:@selector(date)]? [obj1 date] : [obj1 dateOfUpload];
          NSDate *date2 = [obj2 respondsToSelector:@selector(date)]? [obj2 date] : [obj2 dateOfUpload];
          return [date2 compare:date1]; // Objects are reversed to get descending order
      }];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多