我想使用委托将数据从EditPostViewController
传递到NewsfeedTableViewController
,但是在采用func remove(mediaItem:_)
时永远不会调用class NewsfeedTableViewController
。我在做什么错了?
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)
}
}
答案 0 :(得分:2)
在viewDidLoad(:)中实例化的对象以及在“编辑”按钮上单击事件时实例化的对象不是同一对象。进行变量
var editPostVC: EditPostViewController?
使用委托实例化viewDidLoad(:)
editPostVC = storyboard?.instantiateViewController(withIdentifier: "EditPostViewController") as! EditPostViewController
editPostVC.delegate = self
然后在点击事件中展示
navigationController?.pushViewController(editPostVC, animated: true)
或
present(editPostVC, animated: true, completion: nil)
您可以在演示VC之前或之后将数据从演示者传递到演示的VC。
editPostVC.data = self.data
答案 1 :(得分:1)
我建议在NewsfeedTableViewController
中拥有一个财产
var editPostViewController: EditPostViewController?
,然后在实例化EditPostViewController
时分配给它。
这个想法是,它会在NewsfeedTableViewController.viewDidLoad
返回时停止自动释放该类。