【发布时间】:2015-03-27 13:28:16
【问题描述】:
我有一个 swift 项目,我在其中使用通知来传递数据。当我发布通知时,我在消息中编码["data" : data ]
data 属于ParsedMessage 类型,我有多个子类型从它继承而来。
当我收到通知时,我正在使用块样式方法来处理通知。我这样做是因为我想尽量避免拼写错误或忘记在选择器方法末尾添加: 的问题。我开始认为,如果我使用选择器,我最终会得到更清晰的代码,但由于我正在探索一些快速的时髦,我至少想尝试这条路线。
所以无论如何我有两个块来处理子类ParsedMessage 的数据,即AHRSMessage 和LocationMessage
// Define a block to be called by the notification center
lazy var ahrsDataHandler : notificationBlock = { notification in
if let d : Dictionary = notification?.userInfo,
msg : AHRSMessage = d["data"] as? AHRSMessage
{
println (msg.roll)
self.expectation1!.fulfill()
} else {
println("\(__FILE__)::\(__LINE__)Could not parse AHRS Data correctly")
}
}
// Define a block to be called by the notification center
lazy var locationDataHandlerBlock : notificationBlock = { notification in
if let d : Dictionary = notification?.userInfo,
msg : LocationMessage = d["data"] as? LocationMessage
{
println("Latitude: \(msg.lat)")
self.expectation1!.fulfill()
} else {
println("\(__FILE__)::\(__LINE__)Could not parse Location Data correctly")
}
}
最终这两个计算属性被传递到一个调用中:
addObserverForName(...) 需要一个块。
有没有办法使用泛型和/或我错过的东西来简化此代码?
打电话给if let d : Dictionary = notification?.userInfo,
msg : AHRSMessage = d["data"] as? AHRSMessage 似乎有点笨拙
我想知道是否有一些我可以构造的函数,我可以在其中传递一个闭包和一个类型或其他东西,它会在这里“生成”一个与我创建的类似的块。
func generateNotificationBlock<LocationMessage>() 之类的,但我刚刚把自己弄糊涂了。
谢谢
【问题讨论】:
-
我知道这不是您最终要寻找的,但如果您不需要直接使用 userInfo 字典,您可以通过
if let msg = notification.userInfo?["data"] as? AHRSMessage稍微简化一下。
标签: ios swift notifications closures block