alertView:(UIAlertView *)alertView方法在Appdelegate中不起作用

时间:2014-06-23 02:50:50

标签: ios objective-c uialertview appdelegate uialertviewdelegate

我在AppDelegate.m文件中设置了UIAlertView。

但是当我选择警报视图上的按钮时。

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

无效。

我在AppDelegate.h文件中设置了UIAlertViewDelegate。

和我的AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:        (NSDictionary *)launchOptions
        {

         [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];

            NSString *remoteHostName = REACHABILITY_HOST;
            _hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
            [_hostReachability startNotifier];

            return YES;
        }

        - (void) reachabilityChanged:(NSNotification *)note
        {
         if( [Reachability isExistNetwork] == NotReachable)
            {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];
                [alertView show];

            }

        }

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

            switch (buttonIndex) {

                case 0:
                    NSLog(@"ok!");
                    break;

                    // set
                case 1:

                    NSLog(@"set!");
                    NSURL*url=[NSURL URLWithString:@"prefs:root=WIFI"];
                    [[UIApplication sharedApplication] openURL:url];
                    break;

            }
        }

但是

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

没有输入此方法。

有谁知道发生了什么?感谢。

3 个答案:

答案 0 :(得分:9)

您的代码未正确设置警报视图的委托。

您需要更改以下行,以便委托是适当的对象(例如self):

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil         message:@"my message" delegate:nil cancelButtonTitle:@"ok"         otherButtonTitles:@"set",nil];

答案 1 :(得分:2)

您必须替换

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"my message" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:@"set",nil];
[alertView show];

按此行

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"my message" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:@"set",nil];
[alertView show];

您必须将委托设置为self才能调用委托方法。

答案 2 :(得分:1)

检查.h文件中的委托引用。加上UIAlertViewDelegate

@interface YourViewController : UIViewController<UIAlertViewDelegate>