如何使用通知中心将数据从第三视图控制器向后移到第一视图控制器?

时间:2019-12-26 15:46:04

标签: ios swift notificationcenter

我有3个视图控制器。我已经将对象从第一到第二,第二到第三视图控制器传递了,现在在第三视图控制器中编辑一些数据,并尝试使用通知中心将更新的数据对象发送回第一视图控制器。但是我不确定应该使用哪种方法或哪种方法来发布通知,该通知可以将数据对象传递给第一个viewcontrller。

目前,我尝试按照

进行操作
    // third view controller 
    import UIKit

    protocol editContactDelegate: AnyObject {
        func updateContact(contact: Contact)
    }

    class EditViewController: UIViewController {

        @IBOutlet weak var lblName: UILabel!
        @IBOutlet weak var lblPhoneNumber: UILabel!
        @IBOutlet weak var lblEmailID: UILabel!



        var editContact: Contact?

        weak var delegate: editContactDelegate?

        override func viewDidLoad() {
            super.viewDidLoad()

            // Do any additional setup after loading the view.

            lblName.text = editContact?.name
            lblPhoneNumber.text = editContact?.phone
            lblEmailID.text = editContact?.email

        }

        @IBAction func editContact(_ sender: AnyObject) {


///??? which method should i use to post object 
         NotificationCenter.default.post(name: NSNotification.Name("Test"), object: Contact(name: "abc", position: "xyz", email: "updated@gmail.com", phone: "updated number"))
        }

    }

//////////

// first view controller 

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, editContactDelegate {
    func updateContact(contact: Contact) {
        print(contact.email)
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableview.delegate =  self
        self.tableview.dataSource = self

        tableview.register(UINib(nibName: "ContactCell", bundle: nil), forCellReuseIdentifier: "ContactCell")

       NotificationCenter.default
            .addObserver(self,
                         selector:#selector(NotificationAct(_:)),
                         name: NSNotification.Name ("Test"),                                          object: nil)

    }


    @objc func NotificationAct(_ notification: NSNotification) {

        var abc = notification. // how to get object from third viewcontroller ???

    }
}

1 个答案:

答案 0 :(得分:-1)

您需要

let abc = notification.object as! Contact