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:
Get Cocoa® Programming for Mac® OS X, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.