OGeek|极客世界-中国程序员成长平台

标题: ios - UIAlertController -- 在此 block 中强烈捕获 'controller' [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:24
标题: ios - UIAlertController -- 在此 block 中强烈捕获 'controller'

UIAlertController 正在崩溃并显示以下错误消息:

Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x7fb9107674d0>)

在 try catch textFields objectAtIndex 时也会引发警告。

有什么想法吗?

Warning.. Capturing 'controller' strongly in this block is likely to lead to a retail cycle.

我还尝试创建一个 @property (weak) 引用,警告消失了,但应用程序仍然因此崩溃:

-(void)viewWillAppearBOOL)animated
{
    // self.controller = [UIAlertController alloc];

    UIAlertController* controller = [UIAlertController alertControllerWithTitle"Add Alergy To List" message:nil preferredStyleUIAlertControllerStyleAlert)];
    [controller addTextFieldWithConfigurationHandler:^(UITextField * nametextField) {
        _nameTextField.text = [controller.textFields objectAtIndex:0].text;
    }];
    UIAlertAction *save = [UIAlertAction actionWithTitle"Save Data" styleUIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self save:nil];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle"Cancel Action" styleUIAlertActionStyleCancel) handler:nil];
    [controller addAction:save];
    [controller addAction:cancel];
    [self presentViewController:controller animated:YES completion:nil];
}



Best Answer-推荐答案


__weak __typeof(UIAlertController) weakController = controller;
__weak __typeof(UITextField) weakTextField = _nameTextField;

[controller addTextFieldWithConfigurationHandler:^(UITextField *nametextField){

    // nameTextField is the textField being returned in the block
    // if you want to use _nameTextField you need to make that weak too

    nameTextField.text = [weakController.textFields objectAtIndex:0].text;

    // or

    weakTextField.text = [weakController.textFields objectAtIndex:0].text;

}];

关于ios - UIAlertController -- 在此 block 中强烈捕获 'controller',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37347824/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4