0

在下面的代码中,我试图将用户选择的名称添加到arrayDoctors,比如说A,B,然后我将它添加到selectedDoctors数组中。但是第二次我选择医生C,D并将其添加到selectedDoctors数组中,它将先前的对象替换A,BCand D

- (void)doneDoctorSelection:(id)sender
{
   [pop3 dismissPopoverAnimated:YES];
   NSString *str = [arrayDoctors objectAtIndex:0];
   NSString *str1 = [str stringByAppendingString:[NSString stringWithFormat:@" + %d",arrayDoctors.count-1]];

   if([arrayDoctors count] == 1)
    lblDoctor.text = str;
   else
      lblDoctor.text = str1;

   [selectedDoctors addObject:arrayDoctors];
   [selectedDoctorIdList addObject:arrayDoctorsId];

   NSLog(@"selectedDoneDoctors %@ ",selectedDoctors);

}

我究竟做错了什么?

4

2 回答 2

0

啊!!终于找到了解决办法。在将新值放入其中之前,我从 arrayDoctors 中删除了对象,并且我已经在 viewDidLoad 方法中对其进行了初始化。所以发生的事情是当我做 [selectedDoctors addObject:arrayDoctors]; 第二次它在第 1 位替换同一个对象,也是因为它使用相同的内存位置。解决方案是创建一个临时对象。以下是修改后的代码。

- (void)doneDoctorSelection:(id)sender
{
   [pop3 dismissPopoverAnimated:YES];
   NSString *str = [arrayDoctors objectAtIndex:0];
   NSString *str1 = [str stringByAppendingString:[NSString stringWithFormat:@" + %d",arrayDoctors.count-1]];

   NSMutableArray *tempDoctor = [[NSMutableArray alloc]initWithArray:arrayDoctors];
   NSMutableArray *tempDocorId = [[NSMutableArray alloc]initWithArray:arrayDoctorsId
                               ];

   if([arrayDoctors count] == 1)
       lblDoctor.text = str;
   else
       lblDoctor.text = str1;

   NSLog(@"Before Adding %@ ",selectedDoctors);

   [selectedDoctors addObject:tempDoctor];
   [selectedDoctorIdList addObject:tempDocorId];

   //[selectedDoctors addObjectsFromArray:arrayDoctors];
   //[selectedDoctorIdList addObjectsFromArray:arrayDoctorsId];

   NSLog(@"selectedDoneDoctors %@ ",selectedDoctors);

}

感谢您为我指明正确的方向。

于 2013-09-30T13:00:09.293 回答
0

而不是这部分

NSMutableArray *tempDoctor = [[NSMutableArray alloc]initWithArray:arrayDoctors];

[selectedDoctors addObject:tempDoctor];

您可以使用

[selectedDoctors addObject:[arrayDoctors mutableCopy]];
于 2013-09-30T13:03:15.477 回答