首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 多數值求最大值最佳實踐:數組排序法與 Key-Value Coding 替代方案

     編輯:程式設計綜合問答

需求:從 5 個屬性值(itemOneValue...itemFiveValue)中找出最大值,作為上限閾值。本文對比多種實現方式,推薦最簡潔方案。

原始代碼痛點

int v3 = (int)roundf(appDelegate.itemOneValue);
int v4 = (int)roundf(appDelegate.itemTwoValue);
// ... 重複 5 次
// 如何找最大值?

方案一:數組 + 排序(推薦,通用)

NSArray *values = @[
    @(roundf(appDelegate.itemOneValue)),
    @(roundf(appDelegate.itemTwoValue)),
    @(roundf(appDelegate.itemThreeValue)),
    @(roundf(appDelegate.itemFourValue)),
    @(roundf(appDelegate.itemFiveValue))
];

// 升序排序,取最後一個
NSArray *sorted = [values sortedArrayUsingSelector:@selector(compare:)];
NSNumber *maxValue = sorted.lastObject;
int maxInt = [maxValue intValue];

優點:代碼清晰、易擴展、自動處理任意數量值。

方案二:Key-Value Coding 一鍵收集(若屬性名有規律)

NSMutableArray *values = [NSMutableArray array];
for (int i = 1; i <= 5; i++) {
    NSString *key = [NSString stringWithFormat:@"item%dValue", i];
    NSNumber *val = [appDelegate valueForKey:key];
    [values addObject:@(roundf([val floatValue]))];
}
NSNumber *max = [values valueForKeyPath:@"@max.self"]; // KVC 集合運算符

亮點:@max.self 直接獲取最大值,無需排序,性能 O(n)。

方案三:C 級循環(極致性能,嵌入式場景)

float vals[5] = {
    appDelegate.itemOneValue, appDelegate.itemTwoValue,
    appDelegate.itemThreeValue, appDelegate.itemFourValue,
    appDelegate.itemFiveValue
};
float max = vals[0];
for (int i = 1; i < 5; i++) if (vals[i] > max) max = vals[i];
int maxInt = (int)roundf(max);

選型建議

場景推薦
業務邏輯層、可讀性優先方案一(數組排序)
屬性名規律、追求簡潔方案二(KVC @max)
高頻調用、性能敏感方案三(C 循環)

善用集合運算符(@max、@min、@avg),寫出更具表達力的 Objective-C 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved