O'Reilly logo

Cocoa® Programming for Mac® OS X, Fourth Edition by Aaron Hillegass, Adam Preble

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 29. Blocks

Let’s pretend that we’re writing a zombie game. Specifically, we’re working on the zombie AI code. We want a method on our Zombie object to find nearby brains. So we start with this:

@implementation Zombie- (NSArray *)brainsForFlags:(NSInteger)flags{    return [[self game] allBrains];}@end

It’s a good start, but it would be a lot more useful it if returned the brains in order of proximity to the zombie, that is, sorted by the distance between the zombie and the brain. The zombie is hungry, after all. NSArray’s sortedArrayUsingSelector: is usually a great first choice for sorting. It calls the given selector on the objects in the array in order to compare them with their neighbors. For example, NSString provides a compare:

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required