Swift ViewController does not have member named

2019-08-29 09:59发布

问题:

OK, I've been through all of the threads that supposedly deal with this problem and none of them seem to rectify my issue.

Basically I have a tableview setup with core data and when I segue into the next view controller I want to pass some data. As you know the data being passed must already be declared in the destination view controller, which it is. But I keep getting an error saying the ViewController does not have a member name nItem (the variable I am passing).

Here is the section of code that deals with passing the data from the table view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

    if segue.identifier == "editCurrentMed" {
        let cell = sender as UITableViewCell
        let indexPath = tableView.indexPathForCell(cell)
        let addEditMedVC : ViewController = segue.destinationViewController as ViewController
        let nItem : Meds = frc.objectAtIndexPath(indexPath!) as Meds
        addEditMedVC.nItem = nItem
    }

}

And here is the top section of my view controller that is declaring the variable along with the view did load section because that accesses it for when the data is edited.

import UIKit
import CoreData

class addEditMedVC: UIViewController {

    var nItem : Meds? = nil

    @IBOutlet weak var medName: UITextField!
    @IBOutlet weak var dosage: UITextField!
    @IBOutlet weak var timeToTake: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()

        if nItem != nil {
        medName.text = nItem!.name
        dosage.text = nItem!.dose
        nItem!.time = "Morning"
        }

        // Do any additional setup after loading the view.
}

Any help is greatly appreciated. Thanks in advance.

回答1:

Assigning a non-optional value to an optional property should work as expected. But you seem to have confused your class names.

From your prepareForSegue it is evident that the class of the destination view controller is ViewController. In your class file, however, you write it is a subclass of UIViewController called addEditMedVC (which looks more like a variable name rather than the usually capitalized class name).

-> Rename your class to ViewController.



回答2:

Changing the following code:

let addEditMedVC : ViewController = segue.destinationViewController as ViewController
    let nItem : Meds = frc.objectAtIndexPath(indexPath!) as Meds
    addEditMedVC.nItem = nItem

to this code works:

let vc : addEditMedVC = segue.destinationViewController as addEditMedVC
    let nItem : Meds = frc.objectAtIndexPath(indexPath!) as Meds
    vc.nItem = nItem