You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何手动排序NSMutableArray?求助基于NSArray内NSDictionary值的排序方案

Sorting an NSArray of NSDictionaries by Dictionary Values

Hey Matt, I totally get where you're stuck—sorting an array of dictionaries by a specific key value can feel tricky if you're not sure which Foundation APIs to reach for. Let me walk you through two solid, practical approaches that should fit your use case perfectly.

Approach 1: Use NSSortDescriptor (Clean & Simple)

This is the go-to method for basic sorting by a single dictionary key. It’s concise and handles most common cases out of the box.

Example Code:

// Sample array of dictionaries
NSArray *itemsArray = @[
    @{@"productName": @"Laptop", @"price": @999},
    @{@"productName": @"Phone", @"price": @699},
    @{@"productName": @"Tablet", @"price": @399}
];

// Create a sort descriptor targeting your key (e.g., "price")
// Set `ascending:YES` for low-to-high, `NO` for high-to-low
NSSortDescriptor *priceSortDesc = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];

// Apply the descriptor to sort the array
NSArray *sortedArray = [itemsArray sortedArrayUsingDescriptors:@[priceSortDesc]];

Why this works:

  • NSSortDescriptor automatically handles comparison for standard types like NSNumber, NSString, and NSDate (all conform to the NSComparable protocol).
  • You can even chain multiple descriptors if you need to sort by multiple keys (e.g., first by price, then by product name).

Approach 2: Block-Based Comparator (Flexible for Custom Logic)

If you need more control—like handling missing keys, custom value comparisons, or multi-step sorting—use sortedArrayUsingComparator. This lets you write custom comparison logic directly in a block.

Example Code:

NSArray *sortedArray = [itemsArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    // Extract the values you want to compare from each dictionary
    NSNumber *price1 = obj1[@"price"];
    NSNumber *price2 = obj2[@"price"];
    
    // Optional: Handle cases where a dictionary might not have the key
    if (!price1 && !price2) return NSOrderedSame;
    if (!price1) return NSOrderedDescending; // Push items with no price to the end
    if (!price2) return NSOrderedAscending;
    
    // Perform the comparison (adjust based on your value type)
    return [price1 compare:price2];
}];

Customization Tips:

  • For string values (like product names), use [string1 compare:string2 options:NSCaseInsensitiveSearch] to ignore case.
  • For multi-key sorting, add additional comparison checks inside the block (e.g., if prices are equal, compare product names next).

Key Notes:

  • Make sure the values you’re sorting by conform to the NSComparable protocol (most Foundation types do, but double-check custom values if you have any).
  • Both methods return a new sorted array—they don’t modify the original array (since NSArray is immutable). If you’re using NSMutableArray, you can use sortUsingDescriptors: or sortUsingComparator: to modify the array in place.

Hope these examples help you get your array sorted exactly how you need it!

内容的提问来源于stack exchange,提问作者Matt Douhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:06:02