Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C UIKit UIAlertViewDelegate not called

I begin to learn Objective-C uikit , I ran into a problem.UIAlertViewDelegate not called.Can anyone tell me why? thank you!

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface AlertLearn : NSObject <UIAlertViewDelegate>
-(void) showAlertTest;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end

#import "AlertLearn.h"
#import <UIKit/UIKit.h>

@implementation AlertLearn

-(void) showAlertTest{
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"alert" message:@"alert test" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alertView show];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSLog(@"clickedButtonAtIndex = %ld",buttonIndex );
    NSString *buttonTitle = [alertView buttonTitleAtIndex:buttonIndex];
    NSLog(@"clickedButtonAtIndex title = %@",buttonTitle);
}
@end
like image 429
ming nie Avatar asked Sep 16 '26 09:09

ming nie


1 Answers

This is because you are assigning your alert view in a stricter life span than it should be, try making your alert an iVar or property and try again.

@interface AlertLearn : NSObject <UIAlertViewDelegate>
{
UIAlertView * alertView;
}
-(void) showAlertTest;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
@end
...
-(void) showAlertTest{
    alertView = [[UIAlertView alloc] initWithTitle:@"alert" message:@"alert test" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
    [alertView show];

}

and remove the definition from your showAlertTest method.

P.S.: Please note that this type of showing alert view are deprecated as of iOS 8, you should use UIAlertController instead, but if for any reason you need to support iOS 7 and below, well, you should make a strong pointer for your alert.

like image 165
M. Porooshani Avatar answered Sep 17 '26 22:09

M. Porooshani