0

Hi I have an array having 100 element. and each element is of type class Data with the following members:

  • name
  • price
  • stock
  • description

How can I sort the array on based on the price member of class Data?

GWW
  • 39,395
  • 8
  • 104
  • 101
Amit Agrawal
  • 849
  • 3
  • 13
  • 27
  • 1
    What have you tried so far? Have you looked at the NSArray class documentation? There are a bunch of methods for sorting elements. Have you looked the 'Collections Programming Topics' guide, which has descriptions and examples? – Abizern Nov 25 '11 at 04:06
  • Yes, please read the NSArray documentation. Your answer is there, should you bother to read it. – Hot Licks Nov 25 '11 at 04:13
  • 1
    This SO question seems pretty similiar. http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it – SEG Nov 25 '11 at 05:26

2 Answers2

1
NSSortDescriptor *priceDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES] autorelease]; // ascending YES or NO depends on your requirement
NSArray *sortDescriptors = [NSArray arrayWithObject: priceDescriptor];
NSArray *sortedArray = [yourArray sortedArrayUsingDescriptors:sortDescriptors];

also see this

aahsanali
  • 3,507
  • 21
  • 20
0

if you have method for price the object within array class you can use NSComparisonResult:

- (NSComparisonResult) compareprice : (id) element
{
    return [price compare: [element price ]];
}
GustyWind
  • 2,920
  • 3
  • 39
  • 49