遍历的几种方式(OC)

1.for循环遍历

    //for循环遍历
    NSArray *array = @[@1,@2,@3,@4,@5];
    for (int i = 0; i < array.count; i++) {
        NSLog(@"array[i]=%@",array[i]);
    }

    //for循环反向遍历
    for (NSInteger i = array.count-1; i >= 0; i--) {
        NSLog(@"array[i]=%@", array[i]);
    }

2.NSEnumerator遍历法

   //NSEnumerator遍历法
    NSEnumerator *enumerator = [array objectEnumerator];
    id object;
    while ((object = [enumerator nextObject]) != nil) {
        NSLog(@"object=%@",object);
    }

    //NSEnumerator遍历法反向遍历
    NSEnumerator *reverseenu = [array reverseObjectEnumerator];
    id object;
    while ((object = [reverseenu nextObject]) != nil) {
        NSLog(@"object=%@",object1);
    }

3.快速遍历法

   //快速遍历法
   for (NSObject *obj in array) {
       NSLog(@"obj=%@",obj);
   }

   //快速遍历法反向遍历
   for (NSObject *obj in [array reverseObjectEnumerator]) {
       NSLog(@"obj=%@",obj);
   }

4.块枚举法

   //块枚举法
   [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       NSLog(@"idx=%zd,obj=%@",idx,obj);
   }];

   //块枚举法反向遍历
   [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       NSLog(@"idx=%zd,obj=%@",idx,obj);
   }];

你可能感兴趣的:(遍历的几种方式(OC))