/**
* 新型 for 循环遍历
*/
typedef void (^MJClassesBlock)(Class c,BOOL *stop);
- (void)enumerateClassesWithBlock:(MJClassesBlock)block
{
// 1.没有block就直接返回
if (block == nil)return;
// 2.停止遍历的标记
BOOL stop = NO;
// 3.当前正在遍历的类
Class c = [self class];
// 4.开始遍历每一个类
while (c && !stop) {
// 4.1.执行操作
block(c, &stop);
// 4.2.获得父类
c = class_getSuperclass(c);
}
}
// 数组遍历
typedef void (^MJClassesBlock)(id obj, NSInteger index, BOOL *stop);
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSArray * arr =@[ @"01",@"12", @"23",@"34", @"45",@"56", @"67",@"78", @"89",@"90"];
[self enumerateClassesWithBlock:^(NSString * obj,NSInteger index, BOOL *stop) {
NSLog(@"%@===%ld==%d", obj, (long)index, *stop);
if (index == 6) {
*stop = YES;
}
} withArr:arr];
}
-(void)enumerateClassesWithBlock:(MJClassesBlock)block withArr:(NSArray *)arr{
if (block == nil)return;
BOOL stop = NO;
for (NSInteger i =0; i < arr.count; i++) {
id obj = arr[i];
block(obj, i, &stop);
if (stop == YES) break;
}
}
2016-03-29 11:14:33.206 magic[987:63592] 01===0==0
2016-03-29 11:14:33.206 magic[987:63592] 12===1==0
2016-03-29 11:14:33.207 magic[987:63592] 23===2==0
2016-03-29 11:14:33.207 magic[987:63592] 34===3==0
2016-03-29 11:14:33.207 magic[987:63592] 45===4==0
2016-03-29 11:14:33.208 magic[987:63592] 56===5==0
2016-03-29 11:14:33.208 magic[987:63592] 67===6==0
#pragma mark 利用迭代器
void arrayFor4(){
NSArray *array = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
NSEnumerator *enumerator = [array objectEnumerator];
//如果放到遍历之后,则取到空,原因是,遍历完了,就没值了
NSArray *array2 = [enumerator allObjects];
NSLog(@"array2:%@", array2);
//获取下一个需要遍历的元素
id obj = nil;
while (obj = [enumerator nextObject]) {
NSLog(@"obj=%@", obj);
}
}