0

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

//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];
}
4

1 回答 1

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);
于 2013-04-15T03:57:28.397 回答