对象在ARC模式下解除分配

该对象在ARC模式下解除分配并导致崩溃。 我的代码在下面;

BlockAlertView* alert = [BlockAlertView alertWithTitle:title message:message]; [alert setCancelButtonWithTitle:NSLocalizedString(@"No", @"No Button") block:nil]; [alert addButtonWithTitle:NSLocalizedString(@"Yes", @"Yes Button") block:^{ //Do Something }]; [alert show]; 

它显示正确的警报视图(这是自定义的UIView),但当我点击其中一个button崩溃。

崩溃日志;

2015-04-07 22:28:17.065 Test[3213:781570] <BlockAlertView: 0x16bb4160> 2015-04-07 22:33:01.746 Test[3213:781570] *** -[BlockAlertView performSelector:withObject:withObject:]: message sent to deallocated instance 0x16bb4160

这里是BlockAlertView的源代码;

在Github上的BlockAlertView

现在我不能估计任何线索,让我老了。 任何input将不胜感激!

据推测,该代码在转换为ARC之前工作正常。

为了解决这个问题,你需要在-show方法中为self创build一个强引用,并在-dismissWithClickedButtonIndex:animated:在你看到[self autorelease]注释的地方)释放这个引用。

你可以用一个简单的实例variables来做到这一点:

 id _selfReference; 

-show _selfReference self指定给_selfReference

 - (void)show { _selfReference = self; ... 

然后在-dismissWithClickedButtonIndex:animated:中将-dismissWithClickedButtonIndex:animated:设置为nil -dismissWithClickedButtonIndex:animated:在您看到[self autorelease]的两个地方注释掉了。

分配您的alert对象,以生活在当前function以外的地方。 一个简单的可能性就是把它变成一个实例variables。 如果这是不实际的,创build一个实例NSMutableArray *retainedItems; 你分配/ init,并填入这个。

看起来像是该项目的devise缺陷。 这个类名为BlockAlertView因为它实际上并不是UIView的子类。 如果它是一个视图并被添加到视图层次结构中,那么视图层次结构将确保它在被查看的同时保持活动。 因为这是视图保持活着,但创build视图BlockAlertView的对象不被任何东西持有,并在行动被称为BlockAlertView的时间早已逝去。

这将需要你保持一个strong伊娃,以引用这个“控制器”的对象,这是明智的淘汰在完成块伊娃。

 BlockAlertView *alertController = [BlockAlertView alertWithTitle:title message:message]; { [alertController setCancelButtonWithTitle:NSLocalizedString(@"No", @"No Button") block:nil]; __weak __typeof(self) weakSelf = self; [alertController addButtonWithTitle:NSLocalizedString(@"Yes", @"Yes Button") block:^{ //Do Something weakSelf.alertController = nil; }]; [alertController show]; } self.alertController = alertController;