Friday, September 28, 2012

Fast Enumeration Advantage


                                        Fast Enumeration Advantage

Apple has provided NSFastEnumeration protocol by using which one can safely enumerate over the contents of a collection.

The classes which adopt this protocol are : NSArray, NSDictionary, and NSSet

Syntax:

for ( Type newVariable in expression )
{
statements
}
OR
Type existingItem;

for ( existingItem in expression )
{
statements
}

Example 1:Fast Enumeration Forward with Array

NSArray *arr=[NSArray arrayWithObjects:@"One",@"Two",@"Three",nil];

for(NSString *str in arr)
{
NSLog("myString=%@",str);
}

Example 2:Fast Enumeration Backwards with Array

NSArray *arr=[NSArray arrayWithObjects:@"One",@"Two",@"Three",nil];
for (NSString *str in [arr reverseObjectEnumerator])
{
NSLog(@"myString=%@",str);
}

Example 3: Fast Enumeration with Dictionary

NSDictionary *dicObj=[NSDictionary dictionaryWithObjectsAndKeys:@"rajat",@"1",@"rakesh",@"2", @"ashu",@"3",nil];
for (NSString *str in dicObj)
{

NSLog(@"%@,FriendName=%@",str, [dicObj objectForKey:key]);

}

No comments:

Post a Comment