NSMutablearray 导致删除对象崩溃



我运行一个for来选择要删除的对象。我删除一个后,应用程序崩溃了。我已经读到由于索引而无法删除 for 中的对象,所以我在外面删除了它们,但它仍然崩溃。当它在运行时崩溃时,它说阵列是NSArray,但不是,它是一个NSMutablearray。有人知道为什么会这样吗?

这是代码:

NSMutableArray *discardedItems = [NSMutableArray array];
NSInteger catalogo = [[tmpDic objectForKey:@"catalogo"] intValue];
NSInteger documento = [[tmpDic objectForKey:@"documento"] intValue];
for (i=0; i<[self.deletedDocuments count] ; i++) 
{
    if ([[[self.deletedDocuments objectAtIndex:i] objectForKey:@"documento"] intValue] == documento &&
        [[[self.deletedDocuments objectAtIndex:i] objectForKey:@"catalogo"] intValue] == catalogo) 
        [discardedItems addObject:[self.deletedDocuments objectAtIndex:i]];
}
NSLog(@"Dictionaryn%@", self.deletedDocuments);
if (discardedItems != nil)
    [self.deletedDocuments removeObjectsInArray:discardedItems];
您是否将

数组存储在用户默认值中? 从用户默认值获取的对象将是不可变的,即使存储了可变的子类

当它在运行时崩溃时,它说阵列是NSArray,但不是,它是一个NSMutablearray。

不,如果运行时说它是NSArray,则它是NSArray。确保不要将 NSArray 分配给NSMutableArray * deletedDocuments变量。请注意,NSArray的是deletedDocuments,而不是discardedItems

尝试:

for (int i=[self.deletedDocuments count]-1; i>=0 ; i--) 
{
    if ([[[self.deletedDocuments objectAtIndex:i] objectForKey:@"documento"] intValue] == documento &&
    [[[self.deletedDocuments objectAtIndex:i] objectForKey:@"catalogo"] intValue] == catalogo) {
        [self.deletedDocuments removeObjectAtIndex:i];
}
}

最新更新