美文网首页技术好文iOS开发技巧
[iOS ]iOS 开发遍历数组防止crash及提高效率

[iOS ]iOS 开发遍历数组防止crash及提高效率

作者: 沵可安好 | 来源:发表于2020-09-02 14:58 被阅读0次

前言

开发过程中不免需要对数组进行遍历,一般我们都直接用for循环或者for in遍历数组,但是这样的话就容易crash,原因是遍历数组的时候可能一不留神就对数组进行更改。

这边推荐使用block进行遍历数组。例:

 NSMutableArray *tempArray = [[NSMutableArray alloc]initWithObjects:@"12",@"23",@"34",@"45",@"56", nil];
    [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"obj=%@--idx=%lu",obj,(unsigned long)idx);
        if ([obj isEqualToString:@"34"]) {
            *stop=YES;
            [tempArray replaceObjectAtIndex:idx withObject:@"100"];
        }
        if (*stop) {
            NSLog(@"tempArray is %@",tempArray);
        }
    }];

利用block来操作,发现block遍历比for便利快20%左右,这个的原理是这样的:找到符合的条件之后,暂停遍历,然后修改数组的内容。既提高了效率,又防止不小心crash。
附上代码运行控制台输出:


image.png

可以看到只循环了三次就停止了,这样效率就提升了。

相关文章

网友评论

    本文标题:[iOS ]iOS 开发遍历数组防止crash及提高效率

    本文链接:https://www.haomeiwen.com/subject/ikhwsktx.html