NSArray的4种遍历方式

前言:NSArray对应的是java的List,不同的是其元素不能更改,不过其派生类NSMutableArray可以更改,遍历的方式跟java的List基本一样

一.  for循环

 

[objc]  view plain copy 在CODE上查看代码片
 
  1. Student *stu = [Student student];  
  2. NSArray *array = [NSArray arrayWithObjects:stu, @"1",@"2",nil];  
  3. int count = array.count;//减少调用次数  
  4. for( int i=0; i<count; i++){  
  5.     NSLog(@"%i-%@", i, [array objectAtIndex:i]);  
  6. }  

二.  增强for

[objc]  view plain copy 在CODE上查看代码片
 
  1. for(id obj in array){  
  2.     NSLog(@"%@",obj);  
  3. }  

三.  迭代器

 

[objc]  view plain copy 在CODE上查看代码片
 
  1. NSEnumerator *enumerator = [array objectEnumerator];  
  2. id obj = nil;  
  3. while(obj = [enumerator nextObject]){  
  4.     NSLog(@"obj=%@",obj);  
  5. }  

 

四.  Block块遍历

 

[objc]  view plain copy 在CODE上查看代码片
 
    1. [array enumeratorObjectsUsingBlock:  
    2. ^(id obj, NSUInteger index, BOOL  *stop){  
    3.     NSLog(@"%i-%@",index,obj);  
    4.     //若终断循环  
    5.     *stop = YES;  
    6. }];  

你可能感兴趣的:(NSArray)