这是 swift 中的错误还是我的代码不正确(uialertcontroller)?

Is this a bug in swift or my code is not correct(uialertcontroller)?

在这种情况下,我使用 uialertcontroller 来通知用户选择保存、放弃或取消更改。但是在消息出现之后和消失之前,会执行那之后的其他代码(makeNewDocument())。 我不确定是否有解决方案?

 @objc func deleteToNew(_ notification: Notification) {
    if AppDelegate.DocInEditing{
        let dialogMessage = UIAlertController(title: "Save changes?", message: "This file belongs to \(UserManager.shared.firstname)  \(UserManager.shared.lastname). Do you want to save changes?", preferredStyle: .alert)
        
                    let Yes = UIAlertAction(title: "Yes save", style: .default, handler: { (action) -> Void in
                        NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"), object: nil)
                        
                    })
                    let No = UIAlertAction(title: "No Discard changes", style: .default, handler: { (action) -> Void in
                    
                    })
                        
                    let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
                    return
                    }
                    dialogMessage.addAction(Yes)
                    dialogMessage.addAction(No)
                    dialogMessage.addAction(cancel)
            present(dialogMessage, animated: true, completion: nil)
            
    }

    makeNewDocument()
    }

Is this a bug in swift

没有

or my code is not correct(uialertcontroller)?


警报控制器及其操作异步工作,运行 完成时有 completion 参数。在那里调用它

present(dialogMessage, animated: true, completion: makeNewDocument)

或者,如果您只想在其中一个操作中调用 makeNewDocument,请将该行移至操作正文中

let yes = UIAlertAction(title: "Yes save", style: .default, handler: { action in
             NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"), object: nil)
             self.makeNewDocument()                        
          })

旁注:

强烈建议仅在扩展中创建 Notification.Name 常量以利用这些常量的安全性

extension Notification.Name {
    static let saveChanges = Notification.Name(rawValue: "saveChanges")
}

并使用它

let yes = UIAlertAction(title: "Yes save", style: .default, handler: { action in
             NotificationCenter.default.post(name: .saveChanges, object: nil)
             self.makeNewDocument()                        
          })