Ios 点击按钮时UIAlertView崩溃:如何解决?
我有一个类,我通过它的实例来显示如下警报视图:Ios 点击按钮时UIAlertView崩溃:如何解决?,ios,crash,uialertview,exc-bad-access,uialertviewdelegate,Ios,Crash,Uialertview,Exc Bad Access,Uialertviewdelegate,我有一个类,我通过它的实例来显示如下警报视图: - (void)showAlert { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Do you want to try again?" message:nil
- (void)showAlert
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Do you want to try again?"
message:nil
delegate:self
cancelButtonTitle:@"Yes"
otherButtonTitles:@"No", nil];
[alertView show];
}
}
我需要self
作为代理,因为当用户点击警报视图的按钮时,我需要调用alertView:didDismissWithButtonIndex:
来执行一些操作。这通常效果很好,但有时我会遇到这样的崩溃:
SIGSEGV
UIKit-[UIAlertView(Private) modalItem:shouldDismissForButtonAtIndex:]
我猜这是因为代表,不管出于什么原因,被释放了,对吗?还是因为发布的是警报视图?我怎样才能解决这个问题?我需要警报视图有一个代理,我已经阅读了一些相关的帖子,但我找不到适合我的场景的答案
我正在测试iOS 7.0,我不知道这是否与问题有关
提前感谢当其代理被释放时,您似乎点击了警报:
delegate:self
发生这种情况是因为UIAlertView委托属性属于赋值类型(不是弱!)。
因此,您的委托可能会指向已发布的对象
解决方案:
在dealloc方法中,您需要清除alertView的委托
- (void)dealloc
{
_alertView.delegate = nil;
}
但在您需要制作iVar\u alertView并将其用于alertView之前
- (void)showAlert
{
_alertView = ...;
[_alertView show];
}
按如下方式更新您的代码:
- (void)showAlert {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Do you want to try again?"
message:nil
delegate:self
cancelButtonTitle:@"Yes"
otherButtonTitles:@"No", nil];
[alertView show];
}
这是因为您缺少otherbuttonitles
部分的nil
如果您没有添加
nil
这是因为在单击按钮时释放了alertView的委托对象,那么方法分派中缺少sentinel将显示警告。我认为这是SDK的一个缺陷:
@property(nonatomic,assign) id /*<UIAlertViewDelegate>*/ delegate; // weak reference
@属性(非原子,赋值)id/**/delegate;//弱引用
应该是:
@property(nonatomic, weak) id /*<UIAlertViewDelegate>*/ delegate; // weak reference
@property(非原子,弱)id/**/delegate;//弱引用
要解决此问题,请执行以下操作:
请检查您是否在主线程中调用alertview?您可以使用
[NSThread isMainThread]
检查它。我始终在视图控制器中创建显示警报视图的对象。这是一个强大的属性。那么,我可以假设它总是在主线程中调用吗?不幸的是,我不知道怎么造成这次车祸intentionally@Gabriel.Massana如果我在显示警报视图之前选中[NSThread isMainThread]
,我会阻止应用程序达到此崩溃吗?@AppsDev[NSThread isMainThread]
仅用于检查您是否在主线程中。就是查看@Rose评论。谢谢,我的错。。。实际上,我已经添加了nil
,但似乎我从粘贴在这里的代码中删除了它,对不起。我要编辑它,它还在崩溃吗?