NSGenericException,NSMutableArray给出了一些问题

Rob*_*bin 1 iphone exception objective-c nsmutablearray ios

我使用NSMutableArray来存储我的视图上显示的一些UIView对象.我正在使用NSTimer连续调用一个方法来检查该数组的内容并收到一些错误.

这是控制台的堆栈跟踪

2011-03-15 15:23:26.556 something[8166:207] *** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x5d32140> was mutated while being enumerated.(
    "<PDColoredProgressView: 0x5a1c910; baseClass = UIProgressView; frame = (10 98; 20 20); transform = [0, -1, 1, 0, 0, 0]; opaque = NO; tag = 5; layer = <CALayer: 0x5a1a3e0>>"
)'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x023a0919 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x024ee5de objc_exception_throw + 47
    2   CoreFoundation                      0x023a03d9 __NSFastEnumerationMutationHandler + 377
    3   something                           0x00005484 -[somethingViewController renderView] + 1361
    4   Foundation                          0x0005ac99 __NSFireTimer + 125
    5   CoreFoundation                      0x02381d43 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
    6   CoreFoundation                      0x02383384 __CFRunLoopDoTimer + 1364
    7   CoreFoundation                      0x022dfd09 __CFRunLoopRun + 1817
    8   CoreFoundation                      0x022df280 CFRunLoopRunSpecific + 208
    9   CoreFoundation                      0x022df1a1 CFRunLoopRunInMode + 97
    10  GraphicsServices                    0x02c052c8 GSEventRunModal + 217
    11  GraphicsServices                    0x02c0538d GSEventRun + 115
    12  UIKit                               0x002d2b58 UIApplicationMain + 1160
    13  something                           0x00001ef4 main + 102
    14  something                           0x00001e85 start + 53
)
terminate called after throwing an instance of 'NSException'
Run Code Online (Sandbox Code Playgroud)

以下是导致该错误的行.

if(mutableArray.count != 0)
{
    for(PDColoredProgressView *temp in mutableArray)// <- this is the line where the error is occurring.
    {
        if(temp.progress == 0.0f)
        {
            [temp removeFromSuperview];
            [mutableArray removeObject:temp];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

PS.PDColoredProgressViewUIProgressView
我使用上面的类对象来显示进度的子类,然后我从我的视图中删除它.


:关于如何纠正错误的任何建议.
有没有人遇到过这样的例外.需要帮助!!!!!!!!
提前致谢.

gnu*_*chu 7

类似于@ 7KV7的答案.执行此操作的最佳方法是记下要删除的对象的索引(在NSIndexSet中),然后在迭代完成时调用removeObjectsAtIndex.

所以使用你的代码,像(未经测试):

NSMutableIndexSet *indexes;
int count =0;

if(mutableArray.count != 0)
{
    for(PDColoredProgressView *temp in mutableArray)// <- this is the line where the error is occurring.
    {
        if(temp.progress == 0.0f)
        {
            [temp removeFromSuperview];
            [indexes addIndex:count];
        }
        count++;
    }
    [mutableArray removeObjectsAtIndexes:indexes];
}
Run Code Online (Sandbox Code Playgroud)