【发布时间】:2015-10-13 16:02:00
【问题描述】:
我正在尝试在 Swift 中从 appdelegate 调用 ViewController 中的函数?
在Appdelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var first: FirstViewController!
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
FirstViewController.fileurl(url)
first.fileurl(url)
return true
}
}
在FirstViewController.swift
import UIKit
class FirstViewController: UIViewController {
var externalFile: NSURL!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func fileurl(url: NSURL){
externalFile = url
println("externalFile = \(externalFile)")
}
}
在Appdelegate.swift 中,我调用FirstViewController.fileurl() 并尝试调用first.fileurl()。
当我调用 FirstViewController.fileurl(url) 时,它显示 Cannot invoke 'fileurl' with an argument list of type '(NSURL)'。
当我调用 first.fileurl(url) 时,它崩溃并且错误日志是fatal error: unexpectedly found nil while unwrapping an Optional value。
我错过了什么吗?提前致谢。
【问题讨论】:
-
在日志中您是否看到任何显示此错误的变量名称?看起来该方法正在被调用,但
url参数的值为 nil,并且由于强制展开而崩溃 -
is
FirstViewController是导航堆栈中的视图控制器还是可见控制器? -
@developer 我已经打印了
url,它不是零。 -
@Akhilrajtr 它是可见的控制器!
-
@Martin 尝试打印您的
first对象,我猜它的nil