【问题标题】:UIPopovercontroller dealloc reached while popover is still visible在弹出窗口仍然可见时达到 UIPopovercontroller 解除分配
【发布时间】:2023-03-28 15:08:01
【问题描述】:

我向您保证,我确实在 SO 中为我的问题寻找了答案,但它们都没有帮助。在这里,我得到了一个简单的代码,它应该在 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] 到达 while... 错误并且程序崩溃。我没有按照 ARC 进行任何保留、释放或自动释放。从 ARC 中受益时,UIPopoverControllers 是否有任何特殊考虑?

【问题讨论】:

    标签: ios memory-management uipopovercontroller automatic-ref-counting


    【解决方案1】:

    UIPopoverControllers 应该始终保存在实例变量中。为它创建一个强大的属性是一种很好的做法。

    更新:

    从 iOS 8 开始,您应该使用 UIPopoverPresentationController。然后你不需要保留对弹出框的引用,因为它是由演示控制器管理的。

    代码示例(适用于 iPhone 和 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];
    

    【讨论】:

    • 哦,我明白了。但这不是像 UIAlertView 吗?我从来没有它的 ivar,我只是在需要的地方分配初始化它,显示它然后 [用于] 释放。 popovercontroller 有什么不同?
    • @Mikayil alertView 由其父视图保留(与所有视图一样),但 popoverController 不是视图,因此没有父视图,因此不会被任何人保留您不保留它(或将其存储在一个范围比当前方法长的强变量中 - 例如 iVar)。
    • 但我仍然对 UIPopoverController 的保留计数感到困惑。因为我在分配和初始化之前进行了检查。只有当它为零时,我才分配一个新的。但是在第一次分配它之后,我从来没有得到它。我的意思是我调用一次方法。在那里我分配并初始化我的 ivar。下次当我再次调用该方法时,我发现我的 ivar 已经分配。如果 ARC 负责这个,那么它什么时候释放它。还是自动释放它?
    • @Mikayil ivars 在对象被释放或将它们设置为 nil 时由 ARC 释放
    • 但他们没有在文档中提到这一点,在 如何使用 部分他们使用局部变量
    【解决方案2】:

    当函数退出时,没有其他对 popover 控制器的引用,所以它被释放得太早了。

    尝试将其添加为您的班级成员。

    提姆

    【讨论】:

    • 我不应该在它被释放之前先看到它吗?
    【解决方案3】:

    添加@phix23 回答的内容,像这样创建 *poc 属性:

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

    然后改变

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

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

    【讨论】:

    • 您不必将其放入 .h 文件中。这会将其公开,除非您愿意,否则只需将其设为 .m 文件中的属性即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2014-10-03
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多