代码之家  ›  专栏  ›  技术社区  ›  dpigera

Objective-C NSmutableArray:对象排序问题?

  •  0
  • dpigera  · 技术社区  · 16 年前

    我目前有一个名为Station的对象定义为:

    @interface RFStation : NSObject {
    
        NSString *stationID; 
        NSString *callsign; 
        NSString *logo; 
        NSString *frequency;
    @end
    

    我还有一个包含“站”对象列表的NSmutableArray。 我需要一个方法来按“stationstate”属性对这些对象进行排序。

    我实现了这个方法:

    NSComparisonResult compareCallSign(RFStation *firstStation, RFStation *secondStation, void *context) {
        if ([firstStation.stationState compare:secondStation.stationState]){
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
    
    }
    

    并用以下方式称呼它:

    [stationList sortedArrayUsingFunction:compareState context:nil];
    [self.tableView reloadData] 
    

    (数据加载到UITableViewController中)

    有人能告诉我为什么我的NSmutableArray没有被分类吗?

    2 回复  |  直到 16 年前
        1
  •  2
  •   kennytm    16 年前

    -sortedArrayUsingFunction:… 不修改数组。它只是复制数组,对其进行排序,然后返回新的排序数组。

    要对可变数组进行就地排序,请使用 -sortUsingFunction:context: 方法。

    [stationList sortUsingFunction:compareState context:nil];
    [self.tableView reloadData];
    

    顺便说一句,

    1. 这个 -compare: 方法已返回nsComparisonResult。您的功能应该实现为

      NSComparisonResult compareCallSign(...) {
          return [firstStation.stationState compare:secondStation.stationState];
      }
      
    2. 您可以使用nsSortDescriptor。

      NSSortDescriptor* sd = [NSSortDescriptor sortDescriptorWithKey:@"stationState" 
                                                           ascending:YES];
      [stationList sortUsingDescriptors:[NSArray arrayWithObject:sd]];
      [self.tableView reloadData];
      
        2
  •  0
  •   Gary    16 年前

    很明显,您已经将排序方法命名为CompareCallSign,并将CompareState传递给SortedArrayusingFunction