Skip to main content
 首页 » 操作系统

ios之Swift之在展开可选值时意外发现 nil之从委托(delegate)调用变量

2024年01月01日43daizhj

我正在尝试创建我的第一个 iOS 应用

当我尝试从我的委托(delegate) View Controller 访问变量时,出现“在展开可选值时意外发现 nil”的错误

我正在尝试将按下的单元格值设置为目标 Controller 上的标签文本

这是第一个 Controller

class SearchStationViewController: UITableViewController, writeValueBackDelegate { 
    var selectedStation: String! 
    var fromStationValue: String! = "None" 
 
    override func viewDidLoad() { 
        super.viewDidLoad() 
    } 
 
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
        selectedStation = stations[indexPath.row].StationName 
        fromStationValue = selectedStation 
 
        let vc = SelectedStationViewController() 
        vc.fromStationValue = self.fromStationValue 
        vc.delegate = self 
 
        self.dismissViewControllerAnimated(true, completion: nil) 
    } 
} 

我希望它的 label.text 被更改的目标 Controller

protocol writeValueBackDelegate { 
    var fromStationValue: String! {get set} 
} 
 
class SelectedStationViewController: UITableViewController { 
    @IBOutlet weak var stationFrom: UILabel! 
    var delegate: writeValueBackDelegate! = nil 
    var fromStationValue: String! = "None" 
 
    override func viewDidLoad() { 
        super.viewDidLoad() 
 
        stationFrom.text = fromStationValue         
    } 
} 

请您参考如下方法:

所以我只引用我今天早些时候给出的答案:Flappy Bird Coding Error in Swift

您必须使用相应的 xib 或 Storyboard来初始化您的 Controller 。示例:

let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil); 
let vc = storyboard.instantiateViewControllerWithIdentifier("myVCID") as UIViewController; 

(来自 Instantiate and Present a viewController in Swift)

否则你的 View Controller 将不知道任何 socket ,它们将为零。