• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Newbie-Question: Sorting Arrays
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Newbie-Question: Sorting Arrays


  • Subject: Re: Newbie-Question: Sorting Arrays
  • From: Andreas Mayer <email@hidden>
  • Date: Fri, 10 Jun 2005 16:26:37 +0200


Am 10. Jun 2005 um 15:07 Uhr schrieb Christoph Lauterbach:

I want to sort the array in ascending order by the NSDate object and
secondly by the NSString object.

I found the
sortUsingFunction:context:

and the

sortUsingSelector:

function in NSMutableArray, but the are a bit cryptic to me. Maybe one of
you talented guys can give me an example how to sort the array with these
functions.

These are methods, not functions.

To sort an array with sortUsingSelector: your content class (i.e. the class of those objects you store inside the array) needs to implement a comparator method.

The documentation for sortUsingSelector: describes how this method should work:

"The comparator message is sent to each object in the array and has as its single argument another object in the array. The comparator method is used to compare two elements at a time and should return NSOrderedAscending if the receiver is smaller than the argument, NSOrderedDescending if the receiver is larger than the argument, and NSOrderedSame if they are equal."

Let's say the class for your objects is called MyFineObject; then you might want to do implement a method like this:

@implementation MyFineObject

[...]

- (NSComparisonResult)compareWithFineObject:(id)otherObject
{
NSComparisonResult result = NSOrderedSame;
if (self < otherObject) { // pseudo code - do your actual comparison here
result = NSOrderedAscending;
} else if (self > otherObject) { // pseudo code - do your actual comparison here
result = NSOrderedDescending;
}
return result;
}


@end

Then, to sort your array just use [myArrayOfFineObjects sortUsingSelector:@selector(compareWithFineObject:)];


Andreas _______________________________________________ Do not post admin requests to the list. They will be ignored. Cocoa-dev mailing list (email@hidden) Help/Unsubscribe/Update your Subscription: This email sent to email@hidden
References: 
 >Newbie-Question: Sorting Arrays (From: "Christoph Lauterbach" <email@hidden>)

  • Prev by Date: Re: Am I overreleasing something?
  • Next by Date: Archiving selection index paths with core data
  • Previous by thread: Re: Newbie-Question: Sorting Arrays
  • Next by thread: Thumbnail from QT Movie?
  • Index(es):
    • Date
    • Thread