2012-07-12 134 views
2

Possible Duplicate:
Objective-C NSMutableArray mutated while being enumerated?删除对象

我用这个代码在索引中删除一个对象:

-(IBAction)deleteMessage:(id)sender{ 

UIButton *button = (UIButton*) sender; 

for (UIImageView *imageView in imageArray) 
{ 

    if ([imageView isKindOfClass:[UIImageView class]] && imageView.tag == button.tag) 
    { 

     if (imageView.frame.size.height == 60) { 
      x = 60; 
     } 

     if (imageView.frame.size.height == 200) { 
      x = 200; 
     } 

     for (UITextView *text in messagetext) 
     { 

      for (UITextView *name in messagename) 
      { 

       if ([text isKindOfClass:[UITextView class]] && text.tag == button.tag && text.tag== name.tag) 
       { 

     [imageView removeFromSuperview]; 

        [messagename removeObjectAtIndex:button.tag - 1]; 
        [messagetext removeObjectAtIndex:button.tag - 1]; 

       } 
     } 

} 

的错误是:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x704bdb0> was mutated while being enumerated.' 

我注意到的是,如果我删除第一数组中的最后一个对象,并按顺序从最后到冷杉,它的工作原理。但如果我尝试这是不是最后,应用程序崩溃,并给出了错误的索引处移除对象:(1,2,3,4..I删除对象2 ...崩溃了...如果我删除对象4没有崩溃)

回答

6

的一种方式做到这一点是让与数组您打算删除的索引,您执行循环,然后添加索引并删除对象。事情是这样的:

NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init]; 

// Inside your loop 
[indexes addIndex:(button.tag - 1)]; 

//.. 

// After your loop 
[messagename removeObjectsAtIndexes:indexes]; 
[messagetext removeObjectsAtIndexes:indexes]; 

现在,如果你想为两个数组不同的指标只是让另一个NSMutableIndexSet和第二组索引添加到它。另外不要忘记释放indexes,如果你不使用ARC。

+0

OK感谢这个工作得很好,顺便我我们ARC – Alessandro 2012-07-12 18:11:19

1

如果你打算发生变异它不能使用“为每个”迭代式的阵列上(即删除元素),因为它与迭代食堂。如果您真的想在迭代时从数组中移除元素,则需要使用“旧式”迭代。另一个堆栈溢出后here确实展示了如何使用旧风格,让您变异数组的一个好工作。

1

,如果你插入或从中删除对象,则不能“y中的x”的反复使用的阵列上。 要么你必须使用一个良好的醇”老式阵列或者你可以保持您要删除,然后事后删除的对象的引用:

NSObject *messageNameToRemove; 
NSObject *messageTextToRemove; 
for (UITextView *text in messagetext) 
     { 
     for (UITextView *name in messagename) 
     { 

      if ([text isKindOfClass:[UITextView class]] && text.tag == button.tag && text.tag== name.tag) 
      { 

       [imageView removeFromSuperview]; 
       messageNameToRemove = [messagename objectAtIndex:button.tag -1]; 
       messageTextToRemove = [messagetext objectAtIndex:button.tag -1]; 
      } 
     } 

[messagename removeObject:messageNameToRemove]; 
[messagetext removeObject:messageTextToRemove];