0

I am saving images from the camera in an NSMutableArray. When I add one picture, the picture is added to the array. But, the problem is that when I take another picture, the first picture is replaced by the second one. I want to save all of the pictures taken by the camera.

- (IBAction)takePhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self presentViewController:picker animated:YES completion:NULL];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *cameraImage = info[UIImagePickerControllerEditedImage];
    self.tempView.image = cameraImage;
    camImages = [NSMutableArray arrayWithCapacity:10];
    [camImages addObject:self.tempView.image];
    //self.chosenImages=camImages;
    NSLog(@"the image is=%@",camImages);
    [picker dismissViewControllerAnimated:YES completion:NULL];
}
4

2 回答 2

2

拿走 camImages = [NSMutableArray arrayWithCapacity:10];放在viewDidLoad中。

编辑:改用这个:

UIImage *cameraImage = info[UIImagePickerControllerEditedImage];
self.tempView.image = cameraImage;

if(!camImages)camImages = [[NSMutableArray alloc]init];

camImages = [NSMutableArray arrayWithCapacity:10];
[camImages addObject:self.tempView.image];
//self.chosenImages=camImages;
NSLog(@"the image is=%@",camImages);
[picker dismissViewControllerAnimated:YES completion:NULL];
于 2013-07-29T20:23:37.307 回答
1

问题是因为 [NSMutableArray arrayWithCapacity:10]; 实际上在内存中为数组分配了一个新位置,并且您的指针 camImages 指向一个新数组,丢失了您之前分配的旧数组的引用。

因此,每当您拍摄新照片时,都会为数组分配一个新的内存位置,其中仅包含当前图像。

要解决此问题,您应该只分配一次该数组,并为该数组使用相同的内存位置来添加您的图像。

正如 Abdullah Shafique 所指出的,您可以在之前的某个方法中分配该数组一次,例如 viewDidLoad,或者只使用延迟实例化,在您的委托方法中使用 if。

if(!camImages){
     camImages = [NSMutableArray new];
}
于 2013-07-29T20:45:39.190 回答