数组枚举期间应用崩溃 [英] App crash during array enumerating

查看:71
本文介绍了数组枚举期间应用崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有什么问题?我得到

What is wrong with this code ? I get

 Collection <NSCFArray: 0x101e1b6d0> was mutated while being enumerated

这是NSMutableArray,而不是NSArray

It is NSMutableArray, not NSArray

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

    [set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if([obj isEqualToString:@"third"])
         {
             [set removeObjectAtIndex:idx];
         }
     }];

    [pool drain];


推荐答案

您不能在(您正在迭代它,因为迭代器对象也需要更改。您应该将要删除的对象添加到数组中,然后再删除它们。

You can't mutate (change) a collection while you are iterating it because the iterator object would need to change too. You should add the objects you want to remove to an array and remove them afterwards.

NSMutableArray *set = [[NSMutableArray alloc]initWithObjects:@"first", @"second", @"third", @"third", nil];

NSMutableArray *arrayOfObjectsToRemove = [[NSMutableArray alloc] init];
[set enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
 {
     if([obj isEqualToString:@"third"])
     {
         [arrayOfObjectsToRemove addObject:obj];
     }
 }];

[set removeObjectsInArray:arrayOfObjectsToRemove];

[pool drain];

这篇关于数组枚举期间应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆