I have this method that gets called when i press a button and removes a Object from the MutableArray favs. Since it leaves holes in the Array I run into problems later. Is there an easy way to remove those “holes”, or a better way to remove Objects?
- (IBAction)addfavs:(id)sender {
int erase;
for(int i=0;i<favs.count;i++){
if ([favs objectAtIndex:i] == parent) {
[favs removeObjectAtIndex:i];
erase = 1;
}
}
if (!erase) {
[favs addObject:parent];
}
}
[EDIT4]
Great point by user523234
Look at removeObjectIdenticalTo at Apples site for NSMutableArray
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
[EDIT3]
Here is an example of checking with the value (using an integer value), instead of the object itself.
[EDIT2]
The reason it may add an object even if it doesnt remove first is because you never reset your “erase” variable. The first time you set it to 1, it is set for the rest of the time!!! You also never initialize it, thus you never “really” know what the compiler is going to do with the variable the NEXT time your action is called. If it “allocates” the same memory address to your erase variable the “1” will still be resident creating a static condition even though you havent defined it as a static variable!!!
[EDIT]
Didnt originally understand your question. I think I understand now, taking a better look at your code.
Your Code:
What you are doing essentially will SKIP certain items in the list as you increment your counter after each delete. lets say that you remove object 3, your counter now will update to count 4, but 4 is now what was 5, and 3 is now what was 4, so you essentially are skipping item 4 in this case.
Try This:
This will only upgrade the counter if you have NOT deleted the current item.
[ORIGINAL]
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html
Look at the removeObjectAtIndex method notes.
Direct from Apple:
“To fill the gap, all elements beyond index are moved by subtracting 1 from their index.”
This should be being done automatically within Apple’s API. You should not have to do anything, and there really shouldnt be any “holes” left.