我在UIAlertView上有ARCfied简单包装器(我们称之为customAlert),它有自己的代理,如
@protocol customAlert
-(void)pressedOnYES;
- (void)pressedNO
自定义警报本身包含UIAlertView作为强属性而alertView.delegate = self; (customAlert是UIAlertView的委托)
我遇到的问题 - 当调用UIAlertView委托的方法时,会释放customAlert。
f.e
customAlert *alert = [customAlert alloc] initWithDelegate:self];
[alert show]; // it will call customAlert [self.alertView show]
customAlert将在运行循环中释放,并且下一个事件(按下UIAlertView按钮将被发送到解除分配的对象)
我必须以某种方式保留customAlert对象以避免它(我不能使用customAlert实例的属性)
答案 0 :(得分:0)
关于您所面临的问题,作为一个直接修复,而不是将“警报”保持为本地对象,请尝试将其声明为该类的强大属性。
但最好将'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
带有委托方法的View控制器
ViewController.h
#import <UIKit/UIKit.h>
#import "CustomAlert.h"
@interface ViewController : UIViewController <customAlertDelegate>
@end
ViewController.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