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:
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access