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

iOS 根據價格字段對字典數組進行排序的正確方法

     編輯:程式設計綜合問答

在 iOS 中對包含字典的數組按價格字段排序,若價格存儲為字串 (NSString),需使用 localizedStandardCompare: 選擇器正確處理數字字串比較,避免字典序導致 "10" < "2" 的問題。

問題代碼


NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"Price" ascending:YES];
// 錯誤:字串比較 "0.715" vs "10.5" 按字典序,結果錯誤
NSArray *sorted = [symbolArray sortedArrayUsingDescriptors:@[sort]];

解決方案

方法一:使用 localizedStandardCompare: 選擇器 (推薦)


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] 
    initWithKey:@"Price" 
    ascending:YES 
    selector:@selector(localizedStandardCompare:)];
// 關鍵:selector 參數指定比較方法

NSArray *sortedArray = [symbolArray sortedArrayUsingDescriptors:@[sortDescriptor]];

localizedStandardCompare: 會智能識別數字字串並按數值大小排序,支援本地化數字格式。

方法二:預先轉換為 NSNumber (最準確、性能最好)


// 數據獲取階段轉換
for (NSDictionary *dict in originalArray) {
    NSString *priceStr = dict[@"Price"];
    if (priceStr) {
        dict[@"PriceNumber"] = @([priceStr doubleValue]); // 添加數值字段
    }
}

// 排序時使用數值字段
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"PriceNumber" ascending:YES];
NSArray *sorted = [array sortedArrayUsingDescriptors:@[sort]];

方法三:自定義 Comparator 塊 (靈活、現代)


NSArray *sorted = [symbolArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
    NSString *price1 = obj1[@"Price"];
    NSString *price2 = obj2[@"Price"];
    
    if (!price1 && !price2) return NSOrderedSame;
    if (!price1) return NSOrderedDescending; // nil 排最後
    if (!price2) return NSOrderedAscending;
    
    double d1 = [price1 doubleValue];
    double d2 = [price2 doubleValue];
    
    if (d1 < d2) return NSOrderedAscending;
    if (d1 > d2) return NSOrderedDescending;
    return NSOrderedSame;
}];

多字段排序示例


// 先按價格升序,價格相同再按成交量降序
NSSortDescriptor *priceSort = [[NSSortDescriptor alloc] 
    initWithKey:@"PriceNumber" ascending:YES];
NSSortDescriptor *volumeSort = [[NSSortDescriptor alloc] 
    initWithKey:@"VolumeNumber" ascending:NO];

NSArray *sorted = [array sortedArrayUsingDescriptors:@[priceSort, volumeSort]];

關鍵點總結

方法適用場景優點缺點
localizedStandardCompare:字串數字、本地化格式無需預處理、自動處理大數據量較慢
轉 NSNumber 預處理大量數據、頻繁排序性能最好、類型安全需額外內存、數據獲取時處理
Comparator 塊複雜邏輯、多條件完全可控、可處理 nil代碼較長

Swift 版本


let sorted = symbolArray.sorted { dict1, dict2 in
    let price1 = (dict1["Price"] as? NSString)?.doubleValue ?? 0
    let price2 = (dict2["Price"] as? NSString)?.doubleValue ?? 0
    return price1 < price2
}

// 或使用 sortDescriptor
let descriptor = NSSortDescriptor(key: "Price", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
let sorted = (symbolArray as NSArray).sortedArray(using: [descriptor])
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved