Header Ads

Fast Enumeration - Objective C

Fast enumeration is an objective C's features that help in enumerating through a collection. So in order to know about fast enumeration we need know about collection first which will be explained in the following section.

Collection in Objective C

Collections are fundamental constructs : it is used to hold and manage other objects. The whole purpose of a collection is that it provides a common way to store and retrieve objects efficiently.

There are several different type of collections. While they all fulfill the same purpose of being able to hold other objects, they differ mostly in the way objects are retrieved. The most common collections used in Objective C are:
  • NSSet
  • NSArray
  • NSDictionary
  • NSMutableSet
  • NSMutableArray
  • NSMutableDictionary
 If you want to know more about these structures, plz refer data storage in Foundation Framework.

Fast Enumeration Syntax

for( classType variable in collectionObject )
{
    statements;
}

Here is an example for fast enumration.


#import <Foundation/Foundation.h>
int main()
{
     NSArray *arr = [[NSArray alloc] initWithObjects  :@"string1 ", @"string2", @"string3" , nil];
     for( NSString *aString in array )
     {
            NSLog(@"value : %@", aString);
     }
       return 0;
}


Fast Enumeration Backwards

for( classType variable in [collectionObject  reverseObjectEnumerator])
{
    statements;
}

Here is an example for fast enumration.


#import <Foundation/Foundation.h>
int main()
{
     NSArray *arr = [[NSArray alloc] initWithObjects  :@"string1 ", @"string2", @"string3" , nil];
     for( NSString *aString in [array reverseObjectEnumerator])
     {
            NSLog(@"value : %@", aString);
     }
       return 0;
}

you can see in the output  each of the objects in the array is printed but in the reverse order as compared to normal fast enumeration.


No comments:

Powered by Blogger.