【问题标题】:How to sort NSArray of objects based on one attribute如何根据一个属性对对象的 NSArray 进行排序
【发布时间】:2011-09-09 12:10:42
【问题描述】:

我正在尝试按字母顺序对托管对象数组进行排序。它们需要排序的属性是对象的名称(NSString),它是托管属性之一。目前,我将所有名称放在一个字符串数组中,然后使用sortedNameArray = [sortedNameArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];,然后将它们枚举回包含对象的数组中。当两个名称相同时,这就会分崩离析,所以我真的需要能够按一个属性排序。我该怎么做呢?

【问题讨论】:

标签: iphone objective-c ios sorting nsarray


【解决方案1】:

使用 NSSortDescriptor。只需搜索它的文档,您可以直接复制一些非常简单的示例。这是一个简化的例子:

NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:@"MyStringVariableName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:valueDescriptor]; 
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors]; 

就像这样,你有一个排序数组。

【讨论】:

  • 非常感谢,这将节省我的时间,而且在截止日期是一周半的情况下,这意味着很多。
  • 没问题。很高兴我能帮上忙。
  • 是的,谢谢...
【解决方案2】:

您可以使用 NSSortDescriptor 来做到这一点,

例如。

`NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc]initWithKey:@"distance" ascending:YES];`

// 这里我代表距离排序。您应该编写自己的密钥。

NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor];
NSArray *sortedArray=[yourArray sortedArrayUsingDescriptors:descriptors];`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多