-1

I have an array of powders i'd like to sort buy how many pounds of them I have

Each powder is a object with properties one of them being powderQuantity

@interface PowderObject : NSObject <NSCoding>

@property (nonatomic, retain) NSString *powderName;

//Powder Quantity is in pounds

@property (nonatomic, assign) double powderQuantity;

@property (nonatomic, assign) int numberID;

@property (nonatomic, retain) NSString *description;

@end

That is my header for the object I have been storing them in an array by

NSMutableArray *arrayOfPowders = [[PowderDataClass listPowders] mutableCopy];

That line returns all of the powders I have, and then after I get them I'd like to sort them by the weight left of them (powderQuantity). Highest goes first and the least goes last. I've tried using for loops, but have found them very inefficient, and haven't got them to work properly.

Thanks for any help in advance

Larme
  • 18,203
  • 5
  • 42
  • 69
  • 1
    [Magic.](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/doc/uid/20000138-SW8) – The Paramagnetic Croissant Jun 22 '14 at 22:50
  • 1
    Duplicate? http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – Name Here Jun 22 '14 at 23:00

2 Answers2

1

This is actually very doable with NSArray. We'll be using NSSortDescriptors to achieve this, which basically uses key-value coding on an array of properties to sort.

// Note: the key "powderQuantity" must be the exact spelling of your objects' property
NSSortDescriptor *sortByQuantity = [NSSortDescriptor sortDescriptorWithKey:@"powderQuantity" 
                                                                 ascending:YES];
NSArray *sortDescriptors = @[sortByQuantity];
NSArray *sortedPowder = [arrayOfPowders sortedArrayUsingDescriptors:sortDescriptors];

Note that you can add more descriptors to the sortDescriptors as secondary/tertiary/... sorting when two quantities are equal.

Ryan
  • 3,595
  • 3
  • 26
  • 31
0

There are probably a half-dozen ways to do this. Ryan provided one above (using a sort descriptor and sortedArrayUsingDescriptors.)

I tend to prefer the sort methods that take a comparator block, like sortedArrayUsingComparator: (and it's variations)

That code might look like this:

[arrayOfPowders sortedArrayUsingComparator: 
  ^(PowderObject obj1, PowderObject obj2) 
  {
    if (obj1.powderQuantity) < obj2.powderQuantity)
      return NSOrderedAscending;
    else if (obj1.powderQuantity) < obj2.powderQuantity)
      return NSOrderedDescending)
    else
      return NSOrderedSame;
  }
];

It's as much personal preference as anything.

(If you need to sort based on multiple sort keys then Ryan's approach is easier. You just provide 2 sort descriptors in the call to sortedArrayUsingDescriptors.)

Duncan C
  • 115,063
  • 19
  • 151
  • 241