当 popover 仍然可见时,已经达到 UIPopovercontroller 的 deloc

我向你保证,我确实在为我的问题寻找答案,但没有一个是有用的。这里我得到了一个简单的代码,它应该在 UIPopoverController中显示一个 UIImagePickerController:

-(void)takePicture:(id)sender{
UIImagePickerController *picker=[[UIImagePickerController alloc] init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypeCamera;
picker.allowsEditing=YES;
UIPopoverController *poc=[[UIPopoverController alloc]
initWithContentViewController:picker];
[poc presentPopoverFromBarButtonItem:bbItem
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:NO];
}

现在,甚至从我第一次到达 [UIPopoveController dealloc]时... 错误和程序崩溃。我不做任何保留,释放或自动释放按照 ARC。当从 ARC 中受益时,对 UIPopoverControllers有什么特别的考虑吗?

29400 次浏览

When the function exits there are no other reference to the popover controller, so it's deallocated too early.

Try adding it as a member of your class instead.

Tim

UIPopoverControllers should always be held in an instance variable. It is a good practice to create a strong property for it.

UPDATE:

As of iOS 8 you should be using UIPopoverPresentationController. Then you don't need to keep a reference to the popover because it is managed by the presentation controller.

Code example (works both on iPhone and iPad):

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.allowsEditing = YES;
picker.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController* popoverPC = picker.popoverPresentationController;
popoverPC.barButtonItem = bbItem;
popoverPC.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:picker animated:YES completion:nil];

Adding what @phix23 answered, create *poc property like this:

@property (nonatomic, retain) IBOutlet UIPopoverController *poc;

and then change

UIPopoverController *poc = [[UIPopoverController alloc]
initWithContentViewController:picker];

for

self.poc = [[UIPopoverController alloc]
initWithContentViewController:picker];