Challenge with alert


I thought I try adding an alert to the challenge’s delete photo mandate. The alert was a bit tricky because to add a second button to an alert, you have to set a delegate and conform to the UIAlertViewDelegate protocol.

So, I declared conformity to the protocol in ItemDetailViewController.h. I also added a new button to the toolbar along with a connection to a new method -(IBAction)deletePicture:(id)sender; Here’s the rest of the code:

[code]// ItemDetailViewController.m

  • (IBAction)deletePicture:(id)sender { // make self UIAlertView DELEGATE
    UIAlertView * av = [[UIAlertView alloc] initWithTitle:@"Are you sure"
    message:@“you want to delete this image?” delegate:self
    cancelButtonTitle:@“No!” otherButtonTitles:@“Yes”, nil];
    [av show];
    [av release];

// this override (req for UIAlertView delegate) gets called when alert button is pressed
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0)
[alertView dismissWithClickedButtonIndex:0 animated:YES];
else {
NSString *oldKey = [possession imageKey];
// Does the possession have an image?
if (!oldKey) {
return; // Ignore button if no image

    //Delete the image
    [[ImageStore defaultImageStore] deleteImageForKey:oldKey]; 
    // refresh view
    [imageView setImage:nil];


This is the first time I’ve ventured into adopting a protocol on my own, I’m quite pleased with myself! (Comments still welcome.)


[size=85]edit: added release[/size]



The big thing to remember, though, is to be sure the alert view gets released (since you got the reference via alloc, new, or copy).

Apple’s sample code shows this done a few different ways. (It’s nice that searching for “UIAlertView” in the docs also lists sample projects and the files therein containing the referenced method.)

[ol]1. In the UICatalog app, AlertsViewController.m releases the reference immediately after -show.

  1. In the AddMusic app, Classes/MainViewController.m releases the reference in -alertView:clickedButtonAtIndex: (using the passed-in reference to the alert view).

  2. Elsewhere, I’ve seen the UIAlertView created with -autorelease on the end.
    Personally, I like the UICatalog approach best, releasing immediately after showing. Alloc/init, show, release. No fuss, no muss, and no adding to the autorelease pool needlessly.


Thanks as usual, I’ll add a release.