关于您面临的问题,作为一个即时解决方案,不要将“警报”保留为本地对象,而是尝试将其声明为类的强属性。
但最好将“customAlert”保留为“UIAlertView”的子类,而不是将“UIAlertView”作为 customAlert 的属性。
自定义警报类的示例(没有添加太多注释。代码简单且具有自我描述性)。
CustomAlert.h
#import <UIKit/UIKit.h>
@protocol customAlertDelegate<NSObject>
- (void)pressedOnYES;
- (void)pressedNO;
@end
@interface CustomAlert : UIAlertView
- (CustomAlert *)initWithDelegate:(id)delegate;
@property (weak) id <customAlertDelegate> delegate1;
@end
CustomAlert.m
#import "CustomAlert.h"
@implementation CustomAlert
@synthesize delegate1;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (CustomAlert *)initWithDelegate:(id)delegate
{
self = [super initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
if (self) {
//Assigning an object for customAlertDelegate
self.delegate1 = delegate;
}
return self;
}
//Method called when a button clicked on alert view
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex) {
[self.delegate1 pressedOnYES];
} else {
[self.delegate1 pressedNO];
}
}
@end
带有委托方法的视图控制器
视图控制器.h
#import <UIKit/UIKit.h>
#import "CustomAlert.h"
@interface ViewController : UIViewController <customAlertDelegate>
@end
视图控制器.m
#import "ViewController.h"
@implementation ViewController
- (IBAction)pressBtn:(id)sender
{
CustomAlert *alert=[[CustomAlert alloc] initWithDelegate:self] ;
[alert show];
}
- (void)pressedOnYES
{
//write code for yes
}
- (void)pressedNO
{
//write code for No
}
@end