UIAlertController
因此错误消息而崩溃:
不允许在取消分配时尝试加载视图控制器的视图,并且可能导致未定义的行为(< UIAlertController:0x7fb9107674d0>)
还会在尝试捕获textFields objectAtIndex时抛出警告。
有什么想法吗?
警告..捕捉'控制器'这个街区的强势可能导致零售周期。
我还试图创建一个@property (weak)
引用警告消失,但应用程序仍然崩溃:
-(void)viewWillAppear:(BOOL)animated
{
// self.controller = [UIAlertController alloc];
UIAlertController* controller = [UIAlertController alertControllerWithTitle:@"Add Alergy To List" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
[controller addTextFieldWithConfigurationHandler:^(UITextField * nametextField) {
_nameTextField.text = [controller.textFields objectAtIndex:0].text;
}];
UIAlertAction *save = [UIAlertAction actionWithTitle:@"Save Data" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self save:nil];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel Action" style:(UIAlertActionStyleCancel) handler:nil];
[controller addAction:save];
[controller addAction:cancel];
[self presentViewController:controller animated:YES completion:nil];
}
答案 0 :(得分:2)
__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;
}];
答案 1 :(得分:1)
添加
__weak __typeof(UIAlertController) weakController = controller;
在addTextFieldWithConfigurationhandler:
之前。
然后你应该替换
_nameTextField.text = [controller.textFields objectAtIndex:0].text;
与
nameTextField.text = [weakController.textFields objectAtIndex:0].text;
没有_。
_用于内部访问属性。在这里,你必须更新参数
事实是你在一个区块中,如果你想从控制器字段中获取文本,你必须对它进行弱引用。弱控制器将阻止增加保留计数。
答案 2 :(得分:0)
您正在尝试在分配viewcontroller之前加载alertcontroller此警告是因为您正在 viewWillAppear
中直接添加UIAlertController在视图控制器的视图即将添加到视图层次结构
之前调用此方法
总体修改后的代码是bekow:
-(void)viewWillAppear:(BOOL)animated{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIAlertController* controller = [UIAlertController alertControllerWithTitle:@"Add Alergy To List" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
__weak typeof(UIAlertController) *weakcontroller = controller;
[controller addTextFieldWithConfigurationHandler:^(UITextField * nametextField) {
nametextField.text = [weakcontroller.textFields objectAtIndex:0].text;
}];
UIAlertAction *save = [UIAlertAction actionWithTitle:@"Save Data" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
[self save:nil];
}];
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel Action" style:(UIAlertActionStyleCancel) handler:nil];
[controller addAction:save];
[controller addAction:cancel];
[self presentViewController:controller animated:YES completion:nil];
});
}
它没有任何问题。