请帮助我。从数组中删除对象时,我就卡在这里。
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(@"class type %@", [newObj class]);
}
else{
[self.arrSavedImage removeObject:obj];
}
}
谢谢。
答案 0 :(得分:2)
您不应从正在枚举的数组中删除对象。更好的方法是保留要删除的对象列表,然后在枚举完原始数组后删除它们:
NSMutableArray *toDelete = [NSMutableArray new];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
if([newObj isKindOfClass:[UIImage class]]){
NSLog(@"class type %@", [newObj class]);
}
else{
[toDelete addObject:obj];
}
}
for (id obj in toDelete)
[self.arrSavedImage removeObject:obj];
答案 1 :(得分:1)
NSMutableArray *itemsToDelete = [[NSMutableArray alloc] init];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(@"class type %@", [newObj class]);
}
else{
[itemsToDelete addObject:obj];
}
}
[self.arrSavedImage removeObjectsInArray:itemsToDelete];
答案 2 :(得分:0)
在循环中无法删除数组中的对象。
您应该使用现有数组创建一个新数组并从中删除对象。然后用editedArray替换旧数组。
NSMutableArray * editedArray = [[NSMutableArray alloc] initWithArray:self.arrSavedImage];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(@"class type %@", [newObj class]);
}
else{
[editedArray removeObject:obj];
}
}
[self.arrSavedImage setArray:editedArray];
editedArray = nil;