1

uiimagepickerview 控制器在 iphone 中创建内存泄漏 - 为什么?

尝试在您的应用程序中实现 ui 图像选择器视图控制器并对其进行调试。您会在应用程序中发现内存泄漏。为什么 ui 图像选择器视图控制器会产生内存泄漏。


-(void)addPhotos:(id)sender
{
    if(imagePickerController==nil){ 
          imagePickerController=[[UIImagePickerController alloc]init];
          imagePickerController.delegate=self;
          imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        imagePickerController.allowsImageEditing=YES;
          imagePickerController.navigationBar.barStyle=UIBarStyleBlackOpaque;
    }
[self.navigationController presentModalViewController:imagePickerController animated:YES];
}

我的视图控制器的 dealloc。


- (void)dealloc {
if(PhotoDateArray!=nil)[PhotoDateArray release];
if(imagePickerController!=nil) [imagePickerController release];
if(objDetail!=nil) [objDetail release];
if(Picimage!=nil) [Picimage release];
if(mySavePhotoController!=nil) [mySavePhotoController release];
if(LoadingAlert!=nil);
[super dealloc];
}

视频链接解释了我是如何得到内存泄漏的。

http://www.yourfilelink.com/get.php?fid=508534

4

4 回答 4

2

即使您有 nil 检查,仍然有可能泄漏内存。我认为这里发生的是您多次调用 alloc / init ,但只释放一次。我猜它addPhoto:连接到一些按钮点击,dealloc 只会在委托试图销毁时被调用一次。这会产生这样的情况:

  • 按钮点击
    • 分配/初始化
  • 按钮点击
    • alloc / init(第一个分配的选择器上的内存泄漏)
  • 关闭窗口
    • dealloc(免费的第二个分配的选择器)

更好的方法可能是 Apple 在PhotoLocationsiPhoneCoreDataRecipes示例中的做法:

UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];

然后收听你的代表的didFinishPickingImageimagePickerControllerDidCancel消息,在这两个地方打电话[self dismissModalViewControllerAnimated:YES];就足够了。

于 2009-09-19T15:28:43.473 回答
1

I can explain this because I was having the same problem.

Don't test memory on the simulator! If you test the apple code on a device the memory problem disappears.

I was having a memory alloc leak which I found in Instruments. All I was doing was opening and closing the image picker (open/cancel) and using Apple code, my code and other people's code, just like yours above.

All were showing the allocation going up and up each time, as if the picker was not being released. If you tried to release it, it would crash (over released).

Then I found a really helpful web page which basically stated:

"This doesn't happen when testing on the device"

So I switched from the simulator and ran the tests on the device. Lo & behold there was no allocation increase and it behaved normally.

This however is totally evil and now we can place no trust in the simulator to do a reliable job.

I want to add this to save people, the time, pain and bewilderment of wondering wtf is going on!

于 2011-01-26T05:00:49.317 回答
1

我不知道其余的代码,但你有发布吗?

[imagePickerController release]
于 2009-09-19T01:09:18.337 回答
1

UIImagePickerControllerPhotoLibrary.framework第一次显示时加载并初始化。在您的应用程序关闭之前,不会回收此内存。

(您发布的代码似乎没有按原样泄漏,但这并不意味着它不会以导致它们的方式与您的应用程序的其余部分交互)

于 2009-09-19T15:07:53.863 回答