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?

3
  • 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? Commented Nov 25, 2011 at 4:06
  • Yes, please read the NSArray documentation. Your answer is there, should you bother to read it. Commented Nov 25, 2011 at 4:13
  • 1
    This SO question seems pretty similiar. stackoverflow.com/questions/805547/… Commented Nov 25, 2011 at 5:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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 ]];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.