从Swift中的其他类调用Method

时间:2015-09-06 22:07:15

标签: ios xcode swift instantiation

我有2个视图控制器类。我想从ViewController调用ViewController2的方法,但是控制台给了我这个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

这是我在ViewController类中的方法:

class ViewController: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {

    @IBAction func testButton(sender: AnyObject) {
        ViewController2().setText("It's a Test!")
    }
}

以下是ViewController2中的一些代码:

class ViewController2: UIViewController {

    @IBOutlet weak var directionsTextField: UITextView!


    func setText(var fieldText:String){
            directionsTextField.text = directionsTextField.text + "\n \n" + fieldText
    }
}

我很乐意为你提供一切帮助! : - )

提前谢谢你:)

编辑:

我也明白了:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 

在setText方法上... 看起来像directionsTextField还没有(??)

2 个答案:

答案 0 :(得分:2)

你非常接近自己搞清楚。崩溃是因为您的directionsTextField尚不存在。作为一个IBOutlet,它在调用viewDidLoad之前就不会存在。你是如何解决这个问题的?

您更改了SecondViewController的API并为其提供了directionsText属性。用这样的东西搞定:

@IBOutlet weak var directionsTextField: UITextView!
var directionsText = ""

override func viewDidLoad() {
    super.viewDidLoad()
    directionsTextField.text = directionsTextField.text + "\n\n\(directionsText)"
}

FirstViewController中,您更改IBAction以匹配SecondViewController的新API:

@IBAction func testButton(sender: AnyObject) {
    let secondController = SecondViewController() // Felt a bit odd creating an instance without having a way of referencing it afterwards.
    secondController.directionsText = "It's a test"
    // Do what you want. (Perhaps pushing your secondController)
}

答案 1 :(得分:1)

尝试第二个ViewController实例时发生错误。因为您需要实现public static void modSort(int[]a, int from, int to) { if(from >= to) { return; } int p = modPartition(a, from, to); modSort(a, from, p); modSort(a, p+1, to); } 方法。

例如:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentTableViewCell
    cell.commentLabel?.text = comments![indexPath.row]

    return cell
}

第二个ViewController:

init

当您尝试实例化ViewController时,执行它的第一个方法是public class FirstViewController : UIViewController { public override func viewDidLoad() { super.viewDidLoad() let secondviewController = SecondViewController().setText("YOURTEXT") } }