I have an app that displays 9 UIImageViews, and I’m adding in the ability for the user to delete them. The code works fine, except I’m having some issues with using tags in interface builder. It seems that my code deletes the image in the ImageView based upon its position in the array. So, if I have 3 UIImageViews, I will set the first UIImageViews tag to 1, the second image view’s tag to 2, and the third to 3. I try to delete the third one first, and I get the error:
Terminating app due to uncaught exception NSRangeException, reason: *‘ -[__NSArrayM removeObjectAtIndex:]: index 3 beyond bounds [0 .. 1]’
This is the code that I’m using:
- (IBAction)deleteButtonPressed:(id)sender {
NSLog(@"Sender is %@", sender);
UIAlertView *deleteAlertView = [[UIAlertView alloc] initWithTitle:@"Delete"
message:@"Are you sure you want to delete this photo?"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[deleteAlertView show];
int imageIndex = ((UIButton *)sender).tag;
deleteAlertView.tag = imageIndex;
}
- (void)alertView: (UIAlertView *) alertView
clickedButtonAtIndex: (NSInteger) buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex]) {
NSLog(@"User Clicked Yes. Deleting index %d of %d", alertView.tag, [array count]);
NSLog(@"The tag is %i", alertView.tag);
[self.array removeObjectAtIndex: alertView.tag];
NSLog(@"After deleting item, array count = %d", [array count]);
NSLog(@"Returned view is :%@, in view: %@", [self.view viewWithTag:alertView.tag], self.view);
((UIImageView *)[self.view viewWithTag:alertView.tag]).image =nil;
}
[self.user setObject:self.array forKey:@"images"];
}
I have to put the first image in the 0 index of the array, but I know that you can’t have a tag of 0 since it is the default tag. So, I have no idea how to get around this issue. Any help is much appreciated, thanks!
I don’t think static tags as index numbers will work for this because, even if you get it right for the first delete, the match-up of tags and array offsets will change if you delete something that’s not the last array element.
You’d be better to write a method to step through the array and return the item with a tag that matches. Or, if you want direct access via a tag, use a dictionary and build the keys using the tags.
Code for tag matching would look something like: