Suppose, I have a mainview, when I click on a button it will load a subview and let that subview starts the flashlight(LED) and then when I return to main view, it will release the sub view and shuts down the flashlight(LED)
- (void)loadView
{
[self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// If torch supported, add button to toggle flashlight on/off
if ([device hasTorch] == YES)
{
// Create an AV session
AVCaptureSession *session = [[AVCaptureSession alloc] init];
// Create device input and add to current session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
[session addInput:input];
// Create video output and add to current session
AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
[session addOutput:output];
// Start session configuration
[session beginConfiguration];
[device lockForConfiguration:nil];
// Set torch to on
[device setTorchMode:AVCaptureTorchModeOn];
[device unlockForConfiguration];
[session commitConfiguration];
// Start the session
[session startRunning];
// Keep the session around
[self setAVSession:session];
[output release];
}
}
Now, when I close the subview it should release it from memory and stops the flashlight.
- (void)viewDidUnload
{
[self.view removeFromSuperview];
[self autorelease];
[AVSession stopRunning];
[AVSession release], AVSession = nil;
[super viewDidUnload];
}
But this viewDidUnload thing is not working, please tell me what I am doing wrong.
Chances are you are retaining the view controller, and it’s deciding to keep the view in memory just in case your app decides to display it again (this is the caching that Caleb mentions in the comment). Just because a view is not visible doesn’t mean it will get unloaded.
If you have a memory leak (and here I mean the VC), obviously it makes sense to fix it.
However, I think your best option for enabling and disabling the flashlight is to do so in viewDidAppear and viewDidDisappear (or their ..will.. variants).