简体   繁体   English

为什么委托不起作用? iOS - 目标 C

[英]Why delegate is not working? iOS - Objective C

I have the following class:我有以下课程:

@interface myClass : NSObject <UIAlertViewDelegate>

@property (strong) UIAlertView *alert;

-(void) displayAlert;
@end

And here the implementation:这里的实现:

#include "myClass.hpp"

@implementation myClass


- (instancetype)init
{
    self = [super init];
    if (self) {
       [self displayAlert];
    }
    return self;
}

- (void)displayAlert{
    dispatch_async(dispatch_get_main_queue(), ^(void){

_alert = [[UIAlertView alloc] initWithTitle:@"title"
                                                                       message:@"body"
                                                                      delegate:self
                                                             cancelButtonTitle:@"YES"
                                                             otherButtonTitles:nil,nil];
                       [_alert show];
    });

}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
   //This method is never called
}
@end

And I create obj of this class this way:我用这种方式创建了这个类的对象:

MyClass *myClass = [MyClass new];

It displays the alert but it don't call the callback function after button click.它显示警报,但在单击按钮后不调用回调函数。

You need to retain the "myClass" variable until at least after the button is tapped, else it will be deallocated and the delegate method would then not be triggered.您需要保留“myClass”变量,直到至少在点击按钮之后,否则它将被释放并且委托方法将不会被触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM