0

please Help me. I stuck here when deleting an object from array.

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];
            }

        }

Thank You.

0

3 Answers 3

2

You shouldn't remove objects from an array you are enumerating over. Better is to keep a list of the objects you want to delete, and then delete them when you've finished enumerating the original array:

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];
Sign up to request clarification or add additional context in comments.

Comments

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];

Comments

0

You can not remove the object in array while in loop.

You should create a new array with existing array and remove objects from it. Then replace the old array with 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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.