Beyond the challenge: sorting and blocks


#1

I implemented the chapter and challenge today, and decided to go one further and sort my possessions in ascending order, in each group.

Thanks to the Apple documentation I figured out the “old” way of doing the sort. I added a method to Possession named sortPrice: and sort in the init:
[possessionsLow sortUsingSelector:@selector(sortPrice:)];
[possessionsHigh sortUsingSelector:@selector(sortPrice:)];

Straightforward and understandable.

Then I wanted to try with blocks – which I also saw searching the docs – so I ended up with the following:

NSComparator possessionSort = ^(id p1, id p2) { int a = [p1 valueInDollars]; int b = [p2 valueInDollars]; if (a < b) return NSOrderedAscending; else if (a > b) return NSOrderedDescending; else return NSOrderedSame; }; [possessionsHigh sortUsingComparator:possessionSort]; [possessionsLow sortUsingComparator:possessionSort];

Is this acceptable style for a block? The documentation examples didn’t cast p1 or p2, so neither did I. I’m familiar with the idea of closures from Lisp, and I’ve used Java’s anonymous functions, but it feels strange to have the variable declarations in this block. But again, Apple doc examples seem to do the same.

In general, I prefer the old way. I like non-block animation transactions better too. I suppose we’ll all be dragged forward to use the new style eventually.

Any thoughts on this implementation?


#2

What is the answer to shi?
I am also interested in sorting possesions array alphabetically.

Thanks.