Advertisements

Extension 15: Foreach Loop


Enumerating through the contents of a collection class is a very common activity. Collection classes in the Foundation framework include NSSet and NSArray. Enumerating is simply the act of going through the collection and getting every value inside—you might do this, for example, if you were doing the same thing to each one, like disabling the buttons in an NSArray of UIButtons. Normally, this would involve a for() loop, like this:

NSArray *array = // Some array
for (int i = 0; i < [array count]; i++)
    [(UIButton *)[array objectAtIndex:i] setEnabled:NO];

This kind of syntax is so common that there is a shorthand way of doing it (known officially in Objective-C as fast enumeration:

NSArray *array = // Some array
for (UIButton *button in array)
    button.enabled = NO;

The key is what goes inside the for() loop. You declare a variable of any type (to avoid a runtime crash, declare to be the type of variable in the array, such as the UIButton shown here, or if is more than one type, you could use id). Then you put the keyword in, followed by the name of the collection. Basically at this point, the new variable you created will be assigned to the “next” value in the collection at every iteration of the loop. In the body of the loop, you can do whatever you want to the variable. Note though that if you need to access the index of the object, you’ll have to go back to the original style.

Advertisements
Previous Post
Leave a comment

2 Comments

  1. Thanks for the tutorial!

    Reply
  1. Learn Objective-C in 24 Days « Programming for iOS

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

Advertisements
  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 222 other followers

  • Back to the Past

    June 2011
    S M T W T F S
    « May   Jul »
     1234
    567891011
    12131415161718
    19202122232425
    2627282930  
  • Time Machine

  • You count!

    • 621,851 views
  • Worldwide Stats

    free counters
  • Advertisements
%d bloggers like this: