gpt4 book ai didi

ios - Swift - App Delegate 不传递数据

转载 作者:行者123 更新时间:2023-11-29 01:14:41 24 4
gpt4 key购买 nike

我正在开发一个应用程序,它的数据来自 URL,这是我正在使用的示例代码AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var fromUrl: String!


func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject)-> Bool {

print("Host: \(url.host!)")
self.fromUrl = url.host!

return true
}

ViewController.swift

import UIKit

class ViewController: UIViewController {

let appDelegate = AppDelegate()

override func viewDidLoad() {
super.viewDidLoad()

print(appDelegate.fromUrl)

}

它正在记录来自应用程序委托(delegate)的 url.host。但是当我尝试从 ViewController.swift 记录 fromUrl 的值时,它返回 nil。你认为问题是什么?谢谢!

最佳答案

当您在 ViewController 中声明 let appDelegate = AppDelegate() 时,您实际上是在实例化 AppDelegate 的另一个实例。这与您实际使用的 ApplicationDelegate 实例不同。尝试使用以下方式获取该引用:

if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
print(appDelegate.fromUrl)
}

关于ios - Swift - App Delegate 不传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35354467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com