Chapter 8: Enumerators

I enjoyed learning about enumerators when going through Head First Design Pattterns, and I think I understand them reasonably well. However, Cocoa has an abstract NSEnumerator class that can be used in a traditional loop like

id instance
NSEnumerator *enum = [myCollection objectEnumerator];
while (instance = [enum nextObject] {
    // do stuff here...

or in a fast enumeration, like this:

id instance
for (instance in myCollection) {
  // do stuff here...

or like this:

for (id instance in myCollection) {
  // do stuff here...

The first benefit of fast enumeration is that you can write less code, giving yourself less opportunity to make a mistake. A second is that, if you have a good implementation, fast enumeration is faster and more efficient.

There’s a lot of good information in this chapter, and I got some more practice debugging strange errors. After entering two classes of the example, compilation gave me one error that I had to use the FileMerge application (in Developer/Applications/Utilities) to find: In the interface file, I had put parentheses around a method name (-(init)); they’re used for the type of the return value, which -init doesn’t have. That’s an odd way to flake out; I’m not sure what it tells me beside the fact that I need practice writing Objective-C programs. Or maybe that I shouldn’t program late at night.

I finished the Enumeration example and got a seemingly strange error at the end: an Program received signal: “EXC_BAD_ACCESS” at the start of one of the enumeration loops. It turned out not to be with the enumeration code at all: I had left the third argument out of the NSLog statement.

NSLog(@"%d: %@", object);

instead of the correct

NSLog(@"%d: %@", count, object);

The stack trace showed that the failure came at objc_msgSend; farther up the stack was the NSLog statement where the error occurred. Unfortunately it only showed the assembly code, not the Objective-C.

Also, note that there’s some commented-out code in the book’s sample code for this chapter that’s marked “Uncomment this code and try it out!” The comments also suggest that you try to guess what it does before running it. It’s not too hard to do so, but the results can be kind of boring if you run the program in its default spot.

This entry was posted in Debugging hints and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s