gpt4 book ai didi

swift - 从 appdelegate 更新 viewcontroller - 最佳实践?

转载 作者:搜寻专家 更新时间:2023-10-31 08:05:18 25 4
gpt4 key购买 nike

我正在尝试在 AppDelegate.swift 中实现 CoreLocation 方法的 iBeacons(方法在 AppDelegate 中实现以确保应用程序后台功能)

在“ViewController.swift”附带的 SingleView 应用程序中,将数据从 AppDelegate 传递到 ViewController 以更新 View (例如 UIImages、UILabels 或 UITableViews)的最佳做法是什么?

我已经成功实现了两种不同的方法:

1) 委托(delegate),通过在 AppDelegate.swift 中触发 Viewcontroller 委托(delegate)方法:

protocol BeaconLocationDelegate { func minorBeaconChanged(minorValue:NSNumber) }

var locationDelegate: BeaconLocationDelegate

locationDelegate?.minorBeaconChanged(nearestBeacon.minor)

ViewController.swift:

在 viewDidLoad 方法中:

(UIApplication.sharedApplication().delegate as AppDelegate).locationDelegate = self

(我发现这看起来很丑——有没有更好的方法将此属性声明为委托(delegate)?)

协议(protocol)实现:

func minorBeaconChanged(minorValue: NSNumber) {
// do fancy stuff here
}

2) 通过在 AppDelegate 中创建对 ViewController 的引用:

let viewController:ViewController = window!.rootViewController as ViewController
viewController.doSomethingFancy()

这两种方法对我来说都很好,但我认为第一种通过委托(delegate)的方法更优雅,并且在您拥有多个 ViewController 时是更好的选择。

有什么建议吗?

最佳答案

我认为第二种解决方案要容易得多。它还确保 View Controller 不会超出内存(“已释放”)并且应用程序委托(delegate)不会尝试联系不存在的对象。

此外,我不理解在多个 Controller 的情况下的委托(delegate)参数。在那种情况下,您将不得不有多个代表,这确实不是一个理想的情况。或者您将不得不从外部将委托(delegate)更改为不同的 View Controller ——这也不是很优雅而且风险很大。

对于多 View Controller 场景,我推荐通过 NSNotificationCenter 进行通知。这是一种失去耦合,可确保只有那些需要使用react的对象才能接收到消息。 View Controller 应该在创建时开始监听通知,并在它们消失时从通知中心注销。

关于swift - 从 appdelegate 更新 viewcontroller - 最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178784/

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