【问题标题】:How can i take NSArray Biggest Object我如何获取 NSArray 最大对象
【发布时间】:2011-10-24 14:10:50
【问题描述】:

我有一个 NSArray 和数组是这样的数字;

NSArray *ratio = [NSArray arrayWithObjects:@"99",@"88",@"77", @"66", @"55", @"44",@"33", @"22",@"11",@"0",@"-11",@"-22",@"-33",@"-44",@"-55",@"-66",@"-77",@"-88",@"-99",@"-100",nil];

我想取最大的物体 99 和最小的物体 -100,我可以这样做吗?

如果条件是这样的最大对象,我将使用;

if ([[ratio objectAtIndex:i] intValue] == 100 ) {

            rd = 0;
            gr = 0.5;
            bl =0;
}

//我想做这个

if ([[ratio objectAtIndex:i] intValue] == biggestobject or smallestobject ) {
      ///.....
}

请帮我的朋友们:( - 现在解决问题,但接下来还有一个问题。

第二个问题:(

NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
NSLog(@"%@",[ratio sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]]);

我对数组进行了排序,但无法从数组中选择最大和最小的对象。我该怎么做?

NSLog 屏幕如下所示; 99, 99, 99, 91, 91, 88, 88, 88, 88, 77, 77, 66, 66, 66,

如何在有序数组中获取 objectforkey:0

【问题讨论】:

    标签: objective-c xcode nsarray


    【解决方案1】:

    一种方法是对数组进行排序并获取第一个和最后一个索引。

    Sort an NSArray in Descending Order

    【讨论】:

      【解决方案2】:

      这会解决您的问题吗:

      NSInteger maxValue = 0, minValue = 0;
      BOOL firstIteration = YES;
      
      for(id item in ratio) {
          NSInteger intValue = [item integerValue];
          if( firstIteration ) {
              maxValue = intValue;
              minValue = intValue;
              firstIteration = NO;
              continue;
          }
      
          if( intValue < minValue ) minValue = intValue;
      
          if( intValue > maxValue ) maxValue = intValue;
       }
      

      【讨论】:

        【解决方案3】:

        编写此方法以按照您的定义对两个字符串进行排序,注意 NSNumericSearchSee Documentation here.

        NSComparisonResult sortNums(NSString *s1, NSString *s2, void *context) {    
                return [s2 compare:s1 options:NSNumericSearch];
            }
        

        然后使用排序:

        NSArray *sorted = [unsorted sortedArrayUsingFunction:sortNums context:nil];
        

        【讨论】:

          【解决方案4】:

          获取值,而不是以下代码:

          NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO];
          NSLog(@"%@",[ratio sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]]);
          

          你需要使用:

          NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: @"self" ascending: NO]; 
          NSArray *sortedArray = [ratio sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
          
          NSLog(@"max item: %@, min item: %@", [soretedArray objectAtIndex:0], [sortedArray lastObject]);
          

          【讨论】:

            猜你喜欢
            • 2011-11-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-12-04
            • 2013-02-15
            • 1970-01-01
            相关资源
            最近更新 更多