当其他所有工作正常时,UIAlertView按钮会导致崩溃

mon*_*eme 3 iphone uialertview uialertsheet

我有一个显示正常的警报视图.在我的标题中,我已经包含了UIAlertViewDelegate,但出于某种原因,每当我点击警报视图上的按钮时,我的应用程序崩溃就会出现严重错误,并说已发送了无法识别的选择器.

任何想法都会有所帮助.我有完全相同的代码在其他类中运行完全没有问题.

这是我的代码:

    -(void)deletePatient
{
 NSLog(@"Delete");
 //Patient *patientInRow = (Patient *)[[self fetchedResultsController] objectAtIndexPath:cellAtIndexPath];
 NSMutableArray *visitsArray = [[NSMutableArray alloc] initWithArray:[patient.patientsVisits allObjects]];
 //cellAtIndexPath = indexPath;
 int visitsCount = [visitsArray count];
 NSLog(@"Visit count is %i", visitsCount);
 if (visitsCount !=0) 
 {
  //Display AlertView
  NSString *alertString = [NSString stringWithFormat:@"Would you like to delete %@'s data and all their visits and notes?", patient.nameGiven];
  UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:alertString message:nil delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No",nil];
  [alert1 show];
  [alert1 release];

 }
 else if (visitsCount ==0) 
 {
  //Do something else
 }

 [visitsArray release];

}

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
 // the user clicked one of the OK/Cancel buttons
 if (buttonIndex == 0)
 {
  NSLog(@"Yes");

 }
 else
 {
  NSLog(@"No");
 }
}
Run Code Online (Sandbox Code Playgroud)

所以我能想到的最好,它与我从UITableViewCell子类调用deletePatient方法,并在我这样做时传递患者对象这一事实有关.这是传递它的代码

-(IBAction)deletePatient:(id)sender
{
    NSLog(@"Delete Patient:%@",patient.nameGiven);
    PatientListTableViewController *patientList = [[PatientListTableViewController alloc] init];
    patientList.patient = patient;
    UITableView *tableView = (UITableView *)[self superview];
    tableView.scrollEnabled = YES;
    [patientList deletePatient];
    menuView.center = CGPointMake(160,menuView.center.y);
    [patientList release];
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*mir 8

您将patientList对象设置为UIAlertView实例的委托,然后将其释放.当用户单击警报按钮时,它会调用[delegate alertView:self clickedButtonAtIndex:buttonIndex],但委托者,patientList已经发布且不再存在.此时变量委托包含垃圾,所以不要惊讶它没有alertView:clickedButtonAtIndex: selector;

只需在alert alertView:clickedButtonAtIndex:方法中释放patientList对象,或在创建/释放外部类时执行patientList创建/释放或仅使用属性:

//在*.h文件中:

...
PatientListTableViewController *patientList;
...
@property(retain) PatientListTableViewController *patientList;
...
Run Code Online (Sandbox Code Playgroud)

//在*.m文件中:@synthesize patientList;

...
self.patientList =  [[PatientListTableViewController alloc] init];
Run Code Online (Sandbox Code Playgroud)