【问题标题】:Get maximum value from NSMutableArray [duplicate]从 NSMutableArray 获取最大值 [重复]
【发布时间】:2014-10-01 12:51:59
【问题描述】:

如何从 NSMutableArray 中获取最大值。值作为 NSString 存储在数组中,如下所示

for(int counter=0; counter<[datesArray count];counter++)
{
    glass = [NSString stringWithFormat:@"%f",[[dbhandler todayData:currentDate] floatValue]];
    [graphGlassesArray addObject:glass];
}

数组名称是graphGlassesArray

【问题讨论】:

  • 您是否尝试过循环遍历并将迄今为止遇到的最大值存储在变量中?

标签: ios objective-c iphone nsmutablearray


【解决方案1】:

您可以使用以下方法从数组中获取最大值:

NSNumber* max = [graphGlassesArray valueForKeyPath:@"max.self"];
float maxFloat = [max floatValue]

【讨论】:

  • 你只比我快一秒...那我就不发表这个想法了。
【解决方案2】:

您还应该尝试使用键值编码 (https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html)。要获取 NSArray 中的最大值,您可以执行 [array valueForKeyPath:@"@max.attribute"]。试试看这个链接http://nshipster.com/kvc-collection-operators/

【讨论】:

    【解决方案3】:
    float max = 0.f;
    for(int counter=0; counter<[datesArray count];counter++)
    {
        glass = [NSString stringWithFormat:@"%f",[[dbhandler todayData:currentDate] floatValue]];
        [graphGlassesArray addObject:glass];
        if(max < [[dbhandler todayData:currentDate] floatValue]) {
            max = [[dbhandler todayData:currentDate] floatValue];
        }
    }
    

    试试这个

    【讨论】:

      【解决方案4】:

      尝试对可变数组进行排序

      NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:NO selector:@selector(localizedCompare:)]; 
      NSString *maxValue = [[graphGlassesArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]] objectAtIndex:0];
      [desc release];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-18
        • 1970-01-01
        • 2013-11-15
        • 1970-01-01
        • 2021-02-20
        • 2017-09-12
        • 2020-04-16
        • 1970-01-01
        相关资源
        最近更新 更多