我以为我做了一些聪明的事,但它不太奏效。计划是拥有一个自定义的 AlertViewDelegate 对象,该对象通过 block 实现 clickedButton 方法。
#import <Foundation/Foundation.h>
@interface AlertViewDelegate : NSObject <UIAlertViewDelegate>
@property (nonatomic,copy) void(^completionBlock)(NSInteger clickedIndex, UIAlertView *alertView);
@end
#import "AlertViewDelegate.h"
@implementation AlertViewDelegate
@synthesize completionBlock;
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
completionBlock(buttonIndex,alertView);
}
@end
然后,在另一个类中:
AlertViewDelegate * del = [[AlertViewDelegate alloc] init];
[del setCompletionBlock:^(NSInteger buttonIndex, UIAlertView *alertView) {
NSLog(@"%d",buttonIndex);
}];
UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"asdg" message:@"asdg" delegate:del cancelButtonTitle:nil otherButtonTitles:@"YES",@"NO", nil];
[view show];
单击按钮时出现 EXC_BAD_ACCESS 错误。我的猜测是委托(delegate)被释放是因为我在一个方法中定义了它(即它不是一个属性)——这是一个公平的结论吗?关于如何修复它而不必在我使用 ie 的每个类中声明 alertviewdelegate 属性的任何建议?
最佳答案
是的 - 这是一个公平的结论。问题是,一旦您离开所在的方法,委托(delegate)就会被 ARC 释放,因为它仅在局部变量中被强引用。为此,您需要保留对委托(delegate)对象的强引用,因为 UIAlertView 只会保留对委托(delegate)的弱引用。
关于ios - 自定义AlertViewDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19104448/