【问题标题】:NSMutableArray sort with object [duplicate]NSMutableArray用对象排序[重复]
【发布时间】:2012-01-12 18:09:34
【问题描述】:

可能重复:
How to sort an NSMutableArray with custom objects in it?

我有一个 NSObject 类型的对象包含 NSMutableArray 的“帖子”对象类型。该帖子对象具有 ID 属性。

MyObject.posts.post.ID = NSInteger;

我想按 ID 对“帖子”NSMutableArray 进行排序。我尝试了几种方法,但无法成功。 任何帮助/示例都会很棒。

谢谢。

【问题讨论】:

  • 能否请您发布一些您尝试过的事情的代码?找出代码中的问题通常比从头开始编写要容易得多。

标签: objective-c cocoa nsmutablearray sorting


【解决方案1】:

您可以实现比较方法,或使用 NSSortDescriptor。

这个问题和答案可能会对你有所帮助。

How to sort an NSMutableArray with custom objects in it?

【讨论】:

  • 请不要简单地发布指向其他问题的链接作为答案。发表评论并将此问题标记为重复。
【解决方案2】:

您可以使用 NSComparator (NSComparator) 对带有块的数组进行排序

-sortedArrayUsingComparator的定义:找到here

MyObject.posts = [MyObject.posts sortedArrayUsingComparator:^(id obj1, id obj2) {
  if (obj1.post.ID > obj2.post.ID)
    return (NSComparisonResult)NSOrderedDescending;
  if (obj1.post.ID < obj2.post.ID)
    return (NSComparisonResult)NSOrderedAscending;
  return (NSComparisonResult)NSOrderedSame;
}];

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多