I'm trying to use a protocol and delegate pattern which will pass the data in my array back to the parent view controller

Viewed 34

I am new to Xcode and am trying to save an array from secondViewController into the View controller. I have a a series of view controllers embedded in a navigation controller so when I click 'back' on the navigation bar I want to keep the data that was collected in an array 'collectionArray' and save to 'collectionArray2' . Here is the protocol delegate method I've tried:

This is in my ViewController where I want the array saved to :

import UIKit

class ViewController: UIViewController {
    
    var collectionArray2: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let controller = secondViewController()
        controller.delegate = self
        
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let first = segue.destination as! secondViewController
        first.collectionArray.append(contentsOf: collectionArray2)
    }
}


extension ViewController: PopupDelegate {
    func popupSelectedView(array: [String]) {
        collectionArray2.append(contentsOf: array)
        
    }
}

This is my secondViewController where I want to take 'collectionArray':

import UIKit

protocol PopupDelegate: class{

    func popupSelectedView(array: [String])
}

class secondViewController: UIViewController {
    
    var exerciseButton: String!
    var collectionArray: [String] = []
    weak var delegate: PopupDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func Exercisess(_ sender: UIButton){
        exerciseButton = sender.currentTitle
        collectionArray.append(exerciseButton!)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.isMovingFromParent {
            delegate?.popupSelectedView(array: collectionArray)
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        let second = segue.destination as! FinalViewController
        second.cellLabelArray.append(contentsOf: collectionArray)
    }
}

Thank you

1 Answers

your problem is that your are referring to a difference instance of secondViewController. Don't set your delegate in viewDidLoad but when you prepare the segue:

    override func viewDidLoad() {
        super.viewDidLoad()
        //let controller = secondViewController() REMOVE THIS
        //controller.delegate = self REMOVE THIS
        
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let first = segue.destination as! secondViewController
        first.collectionArray.append(contentsOf: collectionArray2)
        first.delegate = self // set the delate here
    }
}

by the way, you should name all your classes starting with capital letters, so it should be SecondViewController

Related