iOS 遍历数组、字典的4中方法

方法一:for循环

遍历数组
NSArray *array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6"];
for (int i = 0; i < array.count; i++) {
}
遍历字典
NSDictionary *dict = @{@"A":@"11", @"B":@"22", @"C":@"33"};
NSArray *keysArray = [dict allKeys];
for (int i = 0; i < keysArray.count; i++) {
    NSString *key = keysArray[i];
   //根据键值获取字典中的每一项
    NSString *value = dict[key];
}

方法二:NSEnumerator

遍历数组
NSArray *array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6"];
NSEnumerator *enumerator = [array objectEnumerator];//正向遍历
//NSEnumerator *enumerator = [array reverseObjectEnumerator];//反向遍历
id object;
while ((object = [enumerator nextObject]) != nil) {
}

方法三:快速遍历

遍历数组
NSArray *array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6"];
for (NSString *obj in iosArray) {
}
遍历字典
NSDictionary *dict = @{@"A":@"11", @"B":@"22", @"C":@"33"};
for (NSString *key in dict) {
    //处理字典的键值
    NSString *value = dict[key];
}
注:反向遍历可以使用

for (NSString *obj in [iosArray reverseObjectEnumerator]){}

方法四:基于块的遍历方式(推荐使用,注意循环引用)

遍历数组
NSArray *array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6"];
[iosArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([obj isEqualToString:@"E"]) {
        *stop = YES;
    }
}];

参数说明:

  1. obj表示数组中的元素(可以改成数组中的任意类型)
  2. idx表示元素的下标,
  3. stop可以控制遍历何时停止,在需要停止时令stop = YES即可(不要忘记前面的*)
遍历字典
NSDictionary *dict = @{@"A":@"11", @"B":@"22", @"C":@"33"};
[dic enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL * _Nonnull stop) {
    if ([obj isEqualToString:@"22"]) {
        *stop = YES;
    }
}];

可以直接把key和value的类型修改成NSString类型

反向遍历:
NSArray *array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6"];
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"%@", obj);
    if ([obj isEqualToString:@"E"]) {
        *stop = YES;
    }
}];
并发遍历:
NSArray *array = @[@"0",@"1", @"2", @"3", @"4", @"5", @"6"];
NSMutableArray *tempArray = [NSMutableArray arrayWithArray:array];
[tempArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
    obj = [NSString stringWithFormat:@"_%@", obj];
    [tempArray replaceObjectAtIndex:idx withObject:obj];
    if ([obj isEqualToString:@"_4"]) {
        *stop = YES;
    }
}];

你可能感兴趣的:(iOS 遍历数组、字典的4中方法)