我有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还没有(??)
答案 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")
}
}