Re: NSComparator - sorting objects in a NSMutableArray
shaun <[email protected]>
| Newsgroups | gmane.comp.web.webobjects.devel |
|---|---|
| Message-ID | <1150983057.16962.46.camel@localhost> |
Hi,
On Thu, 2006-06-22 at 07:59 -0400, Mike Schrag wrote:
> EOSortOrdering.sortArrayUsingKeyOrderArray(yourArray, new NSArray
> (EOSortOrdering.sortOrderingWithKey("keypath.to.double.attribute",
> EOSortOrdering.CompareAscending)));
>
Good one Mike. I Didn't think of that even though I use it a lot myself.
Probably due to the fact its buried in a static library of mine and it
was late in the day at the time.
> On Jun 22, 2006, at 3:13 AM, wojingo wrote:
>
> > Hi Matt,
> >
> > Matt Kime wrote:
> >> I have an NSMutableArray populated with objects. I want do sort them
> >> based on a double type property. sortUsingComparator seems to be the
> >> way to go. this means i need to implement a "compare" function in the
> >> object.
> >> this is the first time i'm tackling this technique and i'm finding
> >> the javadocs too terse to understand. does anyone know where i can
> >> find an example of this?
> >
> > This might help.
> > http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html
> >
> > I think the following will work.. However I just wrote it and
> > havent tried it so it probably will have something(s) wrong. :)
> >
> > public int compare(Object o1, Object o2)
> > throws NSComparator.ComparisonException {
> >
> > if (! (o1 instanceof o2) ) {
> > throw new NSComparator.ComparisonException(
> > "null reference or wrong class");
> > }
> >
Looking at it again, the code above is crap. Thats what you get for
coding in Thunderbird email client at the end of a long day I guess.
But now I will do it again - this time using evolution email client! And
its even later! Yeeehaaar! Here goes nothing..
Obviously it should have been something like:
if (! (o1 instanceof MyObject) ) throw ..
if (! (o2 instanceof MyObject) ) throw ..
Regardless of that glaring error in the initial code above the bit that
is important is the conditions and return values below. Which,
unfortunately, are also incorrect :).
At the very least, the code should read OrderedAscending and
OrderedDescending not OrderAscending and OrderDecending. Apart from
that, I think the contract has been fulfilled for compare. Clearly the
easy way out is to use the approach that Mike posted.
> > double d1 = ((MyObject)o1).myDouble;
> > double d2 = ((MyObject)o2).myDouble;
> >
> > if (d1 == d2) return NSComparator.OrderedSame;
> > if (d1 < d2 ) return NSComparator.OrderAscending;
> > return NSComparator.OrderDescending;
> > }
cheers,
- shaun