gpt4 book ai didi

ios - 在类别中实现 UIAlertView 委托(delegate)方法

转载 作者:行者123 更新时间:2023-11-29 03:59:54 25 4
gpt4 key购买 nike

我尝试实现一个处理 uialertview 的 View Controller 类别。它需要实现 -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 并且如果 viewcontroller 也需要显示警报 View ,则不会弄乱。为此,我将 uialertview 的委托(delegate)设置为类别中的虚拟对象而不是 self。但是,当单击警报 View 中的按钮之一时,我的应用程序因 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);

关于ios - 在类别中实现 UIAlertView 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16007198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com