1

这里一个noob问题。两个内存泄漏与UIImagePickerController和UIPopoverController

我有以下代码:

- (IBAction)selectExistingPicture 
{ 
if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) 
{ 
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; 
    imagePicker.delegate = self; 
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 

    UIPopoverController *popVC = [[UIPopoverController alloc] initWithContentViewController: imagePicker]; 
    popVC.delegate = self; 
    [popVC setPopoverContentSize:CGSizeMake(320, 100)]; 
    [popVC presentPopoverFromRect:CGRectMake(39, 356, 320, 100) inView:self.view permittedArrowDirections:1 animated:NO]; 
} 
else 
{ 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error accessing photo library" 
       message:@"Device does not support a photo library" delegate:nil 
      cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; 
    [alert show]; 
    [alert release]; 
} 
} 

但是编译器警告我大约两个潜在的内存泄漏。一个用于imagePicker,另一个用于popVC。有人可以解释什么需要改变以及为什么。我真的很想明白为什么会发生这种情况,所以我可以在将来避免它。

谢谢!

回答

3

您不会在任何地方发布imagePickerpopVC,这就是为什么您的泄漏。你可以在那里添加一个autorelease或release。

选择以下方法之一:

/* this is the method I would suggest */ 
UIPopoverController *popVC = [[[UIPopoverController alloc] initWithContentViewController: imagePicker] autorelease]; 

UIImagePickerController *imagePicker = [[[UIImagePickerController alloc] init] autorelease];  

/* with these, you could potentially over-release somewhere, so be careful */ 

[popVC release]; 

[imagePicker release]; 

而且,请注意你使用[alert release];。相同的概念。

+0

谢谢!我现在明白了。我向imagePicker添加了自动发布并提醒,但是在popVC的一个方法中有一个手动发布的代码(因为它是在自动发布的同时还在崩溃的应用程序) – TrekOnTV2017 2010-12-18 04:26:18