ios - 自定义AlertViewDelegate

标签 ios cocoa-touch delegates

我以为我做了一些聪明的事,但它不太奏效。计划是拥有一个自定义的 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/

相关文章:

ios - 从 .xib 创建的自定义 UITableViewCell 不显示

iphone - iPhone 4 和 iPhone 5 上的不同 map 缩放

ios - 为什么masksToBounds = YES会阻止CALayer阴影?

iphone - 如何查看 nib/xib 文件的代码?

ios - XCode/iOS - AppDelegate 中 ViewController 的引用

javascript - 添加新记录时如何附加委托(delegate)

ios - Swift/XCode 编译 Archive 一个非常小的 App 需要 25 分钟

objective-c - 如何从磁盘中删除使用 NSUserDefaults 保存的对象

iphone - 如何在 iOS 上正确使用 Facebook Graph API

c# - Delegate.DynamicInvoke - 捕获异常