给NSMutableArray创建独立实例

需要一份NSMutableArray的复制,所以我用mutableCopy方法。但是我发现如果修改了复制品中的数据,原版也会跟着改变。不知道其他创建NSMutableArray的方法是什么?

delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
 self.mainImagesArray = [[NSMutableArray alloc]initWithArray:[delegate.arrayForCarCaptureImages mutableCopy]];

修改代码:

UIImage *filteredImage =[[[[self.mainImagesArray objectAtIndex:i]valueForKey:valueVheck] objectAtIndex:j]  copy];
filteredImage =[filteredImage brightness:(1+sliderValue-0.5)];
[[[self.mainImagesArray objectAtIndex:i]valueForKey:valueVheck]removeObjectAtIndex:j];
[[[self.mainImagesArray objectAtIndex:i] valueForKey:valueVheck]insertObject:filteredImage atIndex:j];

一旦执行arrayForCarCaptureImages也会自动改变。

NSArray *copiedArray = [[NSArray alloc] initWithArray:[otherArray copy]];
delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.mainImagesArray = [[NSMutableArray alloc]initWithArray:delegate.mainImagesArray 
                                                  copyItems:YES];


UIImage *filteredImage = self.mainImagesArray[i][valueVheck][j];
filteredImage = [filteredImage brightness:(1+sliderValue-0.5)];
[self.mainImagesArray[i][valueVheck]replaceObjectAtIndex:j 
                                              withObject:filteredImage];

其实你的代码我没太细看,不过给你个方法做参考,看看有没有用。

你的拷贝只是"浅拷贝".所谓的"浅拷贝"就是你只拷贝了原对象的指针. 这时的原对象和新拷贝出来的对象指向同一块内存地址,所以当新对象改变时,原来的对象也会发生变化.反之亦然.