【发布时间】:2015-03-21 03:04:45
【问题描述】:
我正在使用 iBeacons 在 AppDelegate.swift 中实现 CoreLocation 方法(方法在 AppDelegate 中实现以确保应用程序后台功能)
在“ViewController.swift”附带的 SingleView 应用程序中,将数据从 AppDelegate 传递到 ViewController 以更新视图(例如 UIImages、UILabels 或 UITableViews)的最佳实践是什么?
我已经成功实现了两种不同的方法:
1) 委托,通过在 AppDelegate.swift 中触发 Viewcontroller 委托方法:
protocol BeaconLocationDelegate { func minorBeaconChanged(minorValue:NSNumber) }
var locationDelegate: BeaconLocationDelegate
locationDelegate?.minorBeaconChanged(nearestBeacon.minor)
ViewController.swift:
在 viewDidLoad 方法中:
(UIApplication.sharedApplication().delegate as AppDelegate).locationDelegate = self
(我觉得这看起来很丑 - 有没有更好的方法将此属性声明为委托?)
协议实现:
func minorBeaconChanged(minorValue: NSNumber) {
// do fancy stuff here
}
2) 通过在 AppDelegate 中创建对 ViewController 的引用:
let viewController:ViewController = window!.rootViewController as ViewController
viewController.doSomethingFancy()
这两种方法对我来说都很好,但我认为通过委托的第一种方法更优雅,并且一旦你有多个 ViewControllers 是更好的选择。
有什么建议吗?
【问题讨论】:
标签: swift viewcontroller appdelegate delegation