简体   繁体   English

NSMutableArray中的多个图像

[英]Multiple Images in NSMutableArray

I am saving images from the camera in an NSMutableArray. 我正在将相机中的图像保存在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];
}

Take away camImages = [NSMutableArray arrayWithCapacity:10]; 带走camImages = [NSMutableArray arrayWithCapacity:10]; and put it in viewDidLoad. 并将其放在viewDidLoad中。

EDIT: Use this instead: 编辑:改为使用此:

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];

The problem it's because [NSMutableArray arrayWithCapacity:10]; 问题是因为[NSMutableArray arrayWithCapacity:10]; actually allocates a new position in memory for a array, and your pointer camImages are pointing for a new array, losing the reference for the old one you allocated previously. 实际上在内存中为一个数组分配了一个新位置,并且指针camImages指向了一个新数组,从而丢失了先前分配的旧数组的引用。

So, whenever you take a new photo, a new memory position for the array will be allocated, with just the current image. 因此,每当您拍摄一张新照片时,都会为阵列分配一个新的存储位置,并且仅包含当前图像。

To resolve this problem, you should allocate this array only once, and use the same memory position for the array to add your images. 若要解决此问题,您应该只分配一次此数组,并使用该数组的相同内存位置来添加图像。

As Abdullah Shafique pointed, you can allocate this array once in the some previous method, like viewDidLoad, or just use lazy instantiation, with a if in your delegate method. 正如Abdullah Shafique所指出的那样,您可以在以前的某些方法(例如viewDidLoad)中分配此数组一次,或者仅在委托方法中使用if来使用延迟实例化。

if(!camImages){
     camImages = [NSMutableArray new];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM