Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Foreach loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Objective-C === Foreach loops, called [[Objective-C#Fast enumeration|Fast enumeration]], are supported starting in [[Objective-C]] 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc. <syntaxhighlight lang="ObjC"> NSArray *a = [NSArray new]; // Any container class can be substituted for(id obj in a) { // Dynamic typing is used. The type of object stored // in 'a' can be unknown. The array can hold many different // types of object. printf("%s\n", [[obj description] UTF8String]); // Must use UTF8String with %s NSLog(@"%@", obj); // Leave as an object } </syntaxhighlight> NSArrays can also broadcast a message to their members: <syntaxhighlight lang="ObjC"> NSArray *a = [NSArray new]; [a makeObjectsPerformSelector:@selector(printDescription)]; </syntaxhighlight> Where [[Blocks (C language extension)|blocks]] are available, an NSArray can automatically perform a block on every contained item: <syntaxhighlight lang="ObjC"> [myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"obj %@", obj); if ([obj shouldStopIterationNow]) *stop = YES; }]; </syntaxhighlight> The type of collection being iterated will dictate the item returned with each iteration. For example: <syntaxhighlight lang="ObjC"> NSDictionary *d = [NSDictionary new]; for(id key in d) { NSObject *obj = [d objectForKey:key]; // We use the (unique) key to access the (possibly nonunique) object. NSLog(@"%@", obj); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)