在以下代码中,我尝试在arrayDoctors
中添加用户选择的名称,比如A,B
,然后我将其添加到selectedDoctors
数组。但是,第二次选择医生C,D
并将其添加到selectedDoctors
数组时,它会将之前的对象A,B
替换为C
和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);
}
我做错了什么?
答案 0 :(得分:0)
阿!!终于找到了解决方案。我在将新值放入其中之前从arrayDoctors中删除了对象,并且我已经在viewDidLoad方法中对其进行了初始化。所以发生的事情就是我做了[selectedDoctors addObject:arrayDoctors];第二次它在第一个位置替换相同的对象,因为它使用相同的内存位置。解决方案是创建一个临时对象。以下是更改后的代码。
- (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);
}
Thanx指责我正确的方向。
答案 1 :(得分:0)
而不是这部分
NSMutableArray *tempDoctor = [[NSMutableArray alloc]initWithArray:arrayDoctors];
[selectedDoctors addObject:tempDoctor];
您可以使用
[selectedDoctors addObject:[arrayDoctors mutableCopy]];