[英]UIAlertView delegate method clickedButtonAtIndex: is not working
[英]Implementing UIAlertView delegate method in a category
我尝试实现一个处理uialertview的viewcontroller类别。 它需要实现-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
并且如果viewcontroller也需要显示警报视图,则不要搞乱。 为此,我将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];
}
您的问题是这一行:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.