#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; //遍歷數組,字典,集合的幾種方式 //1.for 循環 [self p_forarray]; //2.NSEnumerator [self p_enumerator]; //3.快速遍歷 [self p_forIn]; //4.基於塊的遍歷 [self p_block]; } -(void)p_forarray{ NSArray *array = [NSArray new]; for (int i = 0;i <array.count;i++){ id object = [array objectAtIndex:i]; //object do something } NSDictionary *dic = [NSDictionary new]; NSArray *keyValue = [dic allKeys]; for (int i = 0; i<keyValue.count;i++){ id object = [dic objectForKey:keyValue[i]]; //object do something; } NSSet *set = [NSSet new]; NSArray *objects = [set allObjects]; for (int i = 0;i<objects.count;i++){ id object = objects[i]; // } } -(void)p_enumerator{ NSArray *array = [NSArray new]; NSEnumerator *enumerator = [array objectEnumerator]; id object; while ((object = [enumerator nextObject]) != nil) { //object do something } NSDictionary *dic = [NSDictionary new]; NSEnumerator *dicenumerator = [dic keyEnumerator]; id key; while ((key = [dicenumerator nextObject]) != nil) { id object = dic[key]; } NSSet *set = [NSSet new]; NSEnumerator *setenumerator = [set objectEnumerator]; while ((object = [setenumerator nextObject]) != nil) { // } //反向遍歷 NSArray *arrayRever = [NSArray new]; NSEnumerator *reverEnumer = [arrayRever reverseObjectEnumerator]; while ((object = [reverEnumer nextObject]) != nil) { // } } -(void)p_forIn{ NSArray *array = [NSArray new]; for (id object in array){ } //反向遍歷 for (id object in [array reverseObjectEnumerator]){ } NSDictionary *dic = [NSDictionary new]; for (id key in dic){ id value = dic[key]; } NSSet *set = [NSSet new]; for (id object in set){ } } -(void)p_block{ NSArray *array = [NSArray new]; [array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { BOOL should; if (1){ *stop = YES; }else{ } }]; //dic NSDictionary *dic = [NSDictionary new]; [dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { }]; [dic enumerateKeysAndObjectsUsingBlock:^(NSString *str, NSObject *object, BOOL * _Nonnull stop) { }]; //開啓並行遍歷 [dic enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { }]; //set NSSet *set = [NSSet new]; [set enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) { }]; } @end