我试图让我的应用程序根据用户的 NSUserDefaults 中的数组是否为空来打开不同的 View Controller 。本质上,如果用户之前在应用程序中保存过数据,应用程序将打开到他们可以选择数据的位置。否则,应用程序将打开欢迎屏幕。
但是,当数组为空时,我会看到为欢迎屏幕设置的背景颜色,但看不到我在 Storyboard中布置的文本或按钮。当数组不为空并且数据页应该打开时,我的应用程序崩溃并出现 SIGABRT 错误。我检查了相关 View Controller 的所有 socket ,似乎没有任何东西断开连接。此外,当我注释掉应用程序委托(delegate)中的代码并将数据 View Controller 设置为我的初始启动 View 时,应用程序运行良好。
完整的错误是“Thread 1: signal SIGABRT”,它被标记在 AppDelegate 类行中。
我在应用程序委托(delegate)中使用的代码如下:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
var accounts = loadAccounts()!
if accounts.isEmpty {
let welcomeController = WelcomeViewController()
self.window!.rootViewController = welcomeController
} else {
let tableController = AccountTableViewController()
self.window!.rootViewController = tableController
}
return true
}
func loadAccounts() -> [Account]? {
return NSKeyedUnarchiver.unarchiveObject(withFile: Account.ArchiveURL.path) as? [Account]
}
最佳答案
可能是 UIWindow 设置不正确。
let bounds = UIScreen.main.bounds
self.window = UIWindow(frame: bounds)
self.window?.rootViewController = `your view controller`
self.window?.makeKeyAndVisible()
还有什么可能出错吗?
var accounts = loadAccounts()!
这条线是你的罪魁祸首。我猜正是这个符号 !
。您正在尝试从数据库或文件系统中获取数据,并期望它始终存在。
想一想,这不可能一直都是正确的。
# check if account array is not empty; I would have returned nil if it would be empty and so we can avoid that extra check here.
if let accounts = loadAccounts(), !accounts.isEmpty {
let tableController = AccountTableViewController()
self.window!.rootViewController = tableController
return true
}
let welcomeController = WelcomeViewController()
self.window!.rootViewController = welcomeController
此外,如果您可以提供有关调试控制台中的错误消息的更多信息。这样我就能以更好的方式提供帮助。
关于swift - 尝试劫持 Root View Controller 时收到 SIGABRT 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339135/