在类别中实现UIAlertView委托方法

时间:2013-04-15 03:22:04

标签: ios objective-c uialertview objective-c-category

我尝试实现一个处理uialertview的viewcontroller类。如果viewcontroller还需要显示警报视图,它需要实现-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex并且不要搞砸。为此,我将uialertview的委托设置为类别中的虚拟对象而不是self。但是当点击alertview中的一个按钮时,我的应用程序与exc_bad_access崩溃。下面的代码有什么问题?

//Dummy handler .h

@interface dummyAlertViewHandler : NSObject <UIAlertViewDelegate>

@property (nonatomic, weak) id delegate;

//.m
-(id) initWithVC:(id) dlg
{
    self = [super init];
    if (self != nil)
    {
        self.delegate = dlg;
    }
    return self;
}

-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [self mainMenuSegue]; //There is no problem with the method
    }
}

//Category .h
#define ALERT_VIEW_DUMMY_DELEGATE_KEY "dummy"
@property (nonatomic, strong) id dummyAlertViewDelegate;

//Category .m
@dynamic dummyAlertViewDelegate;

- (void)setDummyAlertViewDelegate:(id)aObject
{
    objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_ASSIGN);
}

- (id)dummyAlertViewDelegate
{
    id del = objc_getAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY);

    if (del == nil)
    {
        del = [[dummyAlertViewHandler alloc] initWithVC:self];
        self.dummyAlertViewDelegate = del;
    }

    return del;
}

-(void) mainMenuSegueWithConfirmation
{
    UIAlertView *ruSure = [[UIAlertView alloc] initWithTitle:@"Confirm leave" 
message:@"Are you sure you want to leave this game?" 
delegate:self.dummyAlertViewDelegate 
cancelButtonTitle:@"No" 
otherButtonTitles:@"Yes", nil];

    [ruSure show];
}

1 个答案:

答案 0 :(得分:1)

你的问题就在这一行:

objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_ASSIGN);

具体而言,OBJC_ASSOCIATION_ASSIGN会导致您的关联对象无法保留。为了让您的设计完全正常工作,您需要将其更改为OBJC_ASSOCIATION_RETAIN,如下所示:

objc_setAssociatedObject(self, ALERT_VIEW_DUMMY_DELEGATE_KEY, aObject, OBJC_ASSOCIATION_RETAIN);