Objective-c – UIAlertView without any buttons

iphoneobjective cuialertview

I wanted to know whether the following code is okay or not. I am trying to dismiss the alertView automatically after 2 seconds (and without any buttons in the alertView) from the "timedAlert" method.

    //this is in another method  
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Login successful." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];
    [alert release];
    [self timedAlert];
}

-(void)timedAlert
{
    [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:2];
}

-(void)dismissAlert:(UIAlertView *) alertView
{
    [alertView dismissWithClickedButtonIndex:nil animated:YES];
}

If the cancelButton of the alertView is set to "nil", how will the "[alertView dismissWithClickedButtonIndex:0 animated:YES];" thing work??? I tried making the cancelButton "nil" and it worked, but cant figure out how….

P.S: I call the timedAlert method from another

Any help is appreciated! Thank you!

Best Answer

First let me say it would be better if you handle this with a custom view, but with that said the problem looks to be with

[alert release];

You are releasing the object before you are done with it (I am surprise it does not crash).

Do something like this

// other code
alert = [[UIAlertView alloc] initWithTitle:nil message:@"Login successful." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    [alert show];
    [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:3.0f];
}

-(void)dismissAlert:(UIAlertView *) alertView
{
    [alertView dismissWithClickedButtonIndex:nil animated:YES];
    [alertView release];
}
Related Topic