如何手动排序NSMutableArray?求助基于NSArray内NSDictionary值的排序方案
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:
NSSortDescriptorautomatically handles comparison for standard types likeNSNumber,NSString, andNSDate(all conform to theNSComparableprotocol).- 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
NSComparableprotocol (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
NSArrayis immutable). If you’re usingNSMutableArray, you can usesortUsingDescriptors:orsortUsingComparator:to modify the array in place.
Hope these examples help you get your array sorted exactly how you need it!
内容的提问来源于stack exchange,提问作者Matt Douhan

