05.01.2013 Views

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

Mac OS X Leopard - ARCAism

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

- (void)privateMethod;<br />

{<br />

[self privateHelper];<br />

// ...<br />

}<br />

- (void)privateHelper;<br />

{<br />

// ...<br />

}<br />

@end<br />

NOTE Class extensions, unlike protocols, are completely anonymous and cannot be adopted<br />

by multiple classes.<br />

Fast Enumeration<br />

CHAPTER 26 MAC <strong>OS</strong> X DEVELOPMENT: OBJECTIVE-C 505<br />

Iterating over a collection is one of the most common tasks in programming. Traditionally, C<br />

accomplishes this via the standard for loop:<br />

NSArray *objects = [self methodThatReturnsAnArrayOfObjects];<br />

NSUInteger objectIndex;<br />

for (objectIndex = 0; objectIndex < [objects count]; objectIndex++) {<br />

NSObject *object = [objects objectAtIndex:objectIndex];<br />

// ...<br />

}<br />

This is effective, but it’s a lot to type, it requires an additional method call, and worst of all<br />

it works only for arrays. As such, Cocoa provides the NSEnumerator class, which enables the following:<br />

NSArray *objects = [self methodThatReturnsAnArrayOfObjects];<br />

NSEnumerator *objectEnumerator = [objects objectEnumerator];<br />

NSObject *object = nil;<br />

while ((object = [objectEnumerator nextObject])) {<br />

// ...<br />

}<br />

For all the object-oriented goodness that enumerators bring, they are slow and require<br />

making a copy of every object. They also suffer from the same kind of redundant verbosity as the<br />

C iteration loop. Objective-C 2.0 introduces the ultimate solution to the looping problem:<br />

NSArray *objects = [self methodThatReturnsAnArrayOfObjects];<br />

for (NSObject *object in objects) {<br />

// ...<br />

}<br />

Fast enumeration is both more concise and more readable than either of the other methods.<br />

It is backed by the NSFastEnumeration protocol, so it can work with any collection, including your<br />

own. It is also highly optimized, so it is not only faster than traditional enumeration, but it is also<br />

faster than C iteration.<br />

Finally, fast enumeration adds the benefit of a mutation check, which ensures collections do<br />

not change during enumeration. This makes it possible to perform multiple enumerations simultaneously.<br />

This is part of a general move toward thread safety as multiprocessor technology<br />

continues to form an important part of the platform.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!