bibscy
bibscy

Reputation: 2708

Why delegate event is not received swift?

I would like to pass data from EditPostViewController to NewsfeedTableViewController using delegates, but func remove(mediaItem:_) is never called in the adopting class NewsfeedTableViewController. What am I doing wrong?

  NewsfeedTableViewController: UITableViewController, EditPostViewControllerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()

   //set ourselves as the delegate
   let editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as! EditPostViewController
    editPostVC.delegate = self
 }

  //remove the row so that we can load a new one with the updated data
      func remove(mediaItem: Media) {
        print("media is received heeeee")
        // it does't print anything
    }
}


   extension NewsfeedTableViewController {

//when edit button is touched, send the corresponding Media to EditPostViewController
     func editPost(cell: MediaTableViewCell) {

    let editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as? EditPostViewController
     guard let indexPath = tableView.indexPath(for: cell) else {
        print("indexpath was not received")
        return}

     editPostVC?.currentUser = currentUser
     editPostVC?.mediaReceived = cell.mediaObject
     self.navigationController?.pushViewController(editPostVC!, animated: true)
 }




 protocol EditPostViewControllerDelegate: class {
   func remove(mediaItem: Media)
 }

 class EditPostViewController: UITableViewController {

  weak var delegate: EditPostViewControllerDelegate?

   @IBAction func uploadDidTap(_ sender: Any) {

    let mediaReceived = Media() 
    delegate?.remove(mediaItem: mediaReceived)
  }
}

Upvotes: 0

Views: 86

Answers (2)

JAHID HASAN POLASH
JAHID HASAN POLASH

Reputation: 191

The objects instantiating in viewDidLoad(:) and on edit button click event are not the same objects. Make a variable

var editPostVC: EditPostViewController?

instantiate in in viewDidLoad(:) with delegate

editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as! EditPostViewController
editPostVC.delegate = self

and then present it on click event

navigationController?.pushViewController(editPostVC, animated: true)

or

present(editPostVC, animated: true, completion: nil)

you can pass data from presenter to presented VC before or after presenting the VC.

editPostVC.data = self.data

Upvotes: 2

Faisal Memon
Faisal Memon

Reputation: 3454

I suggest having a property in NewsfeedTableViewController

var editPostViewController: EditPostViewController?

and then assigning to that when you instantiate the EditPostViewController.

The idea is that it stops the class being autoreleased when NewsfeedTableViewController.viewDidLoad returns.

Upvotes: 1

Related Questions