如何在Swift中传递一个nil通知变量

时间:2017-08-08 00:27:16

标签: ios swift nsnotificationcenter nsnotification

我对Swift比较陌生,所以我的头脑经常在编码时返回到Objective-C解决方案。

我正在为播客播放器编码音频单元。这里面有一个自定义的UIView滑块和一个音频管理器单例。当通过发送通知手动更改滑块时,滑块与其父UITableViewCell通信,然后单元与音频管理器通信以播放/暂停音频。

我正在编写代码以使音频对滑块的手动更改作出反应,为此我将滑块上的百分比拖动发送到Cell,以便它可以播放适当的音频。

// Notification sent containing information - notification sent from SlideView
NotificationCenter.default.post(name: Notification.Name("SlidebarManuallyMovedNotification"), object: nil, userInfo: ["percent": Double(self.getCurrentPercent())])

// Notification observed in UITableViewCell
NotificationCenter.default.addObserver(self, selector: #selector(self.refreshCell(notification:)), name: Notification.Name("SlidebarManuallyMovedNotification"), object: nil)

发送和接收通知工作正常:

// Some info needs to be refreshed depending on the cell state
func refreshCell(notification: NSNotification) {

// If we have user information it means we have manually changed the position so want to refresh the information
    if (notification.userInfo != nil) {

... // I then run code depending on whether we have user info or not

如您所见,我收到通知,然后移动以刷新单元格。

现在的问题来自于尝试从我的UITableViewCell内部手动调用refreshCell:

// 1
self.refreshCell(notification: nil)
// 2
self.refreshCell(notification: NSNotification())
// 3
let notify: NSNotification = NSNotification()
self.refreshCell(notification: notify)

我在Objective-C中尝试了第一种方法,通常很容易加载带有或不带信息initWithCellInfo: (NSDictionary *) userInfo的不同视图。在这种情况下,我想做同样的事情,在没有任何userInfo的情况下调用函数,这样我就可以稍微不同地刷新我的单元格。

然后我尝试添加一个空通知,以便传入它并返回nil userInfo。当我这样做时,我收到以下警告:

[NSConcreteNotification init]: should never be used'

这指向this回答,但我不想创建实际通知,只是指向虚拟调用该功能。

其他想法: 我想过要创建两个函数:

func refreshCellInfo(notification: NSNotification) { 

    let userInfo = "foo"
    self.refreshCellInfo(userInfo)
}

func refreshCellInfo(info: String) { 

然后我可以调用refreshCellInfo("")并添加一个if语句来检查字符串而不是通知。

这似乎不是一种非常优雅的方式,添加一个完全不必要的功能,并捏造if语句来解决问题而不是理解它。

如果有人能够解释这里发生了什么,以及是否有一个很好的解决方案,我会非常感激,我觉得这真的突出了我的理解上的差距,虽然我可以修补我真正想要学习的问题从它作为开发人员前进。

1 个答案:

答案 0 :(得分:1)

你需要稍微重构一下。将接收通知的函数与刷新单元格的函数分开,然后从第一个函数中调用第二个函数。

你可以这样说:

func receiveDragNotification(notification: NSNotification) {
     self.refreshCellInfo(notification)
}

func refreshCellInfo(_ notification: Notification?) {
     //  process update
}

现在,由于refreshCellInfo中的通知参数是可选的,因此您可以根据需要传递nil

但实际上,您应该进一步分离功能,以便您有一个负责接收通知和更新数据模型的功能,以及第二个负责根据数据模型更新单元格的功能(注意您还没有提供所有细节,所以我使用的是虚构的 self.position作为数据模型)

 func receiveDragNotification(notification: NSNotification) {
     // update data model based on notification 
         self.position = someDataFromNotification
     //  Now refresh the cell based on this new data
     self.refreshCellInfo()
}

func refreshCellInfo() {
     // use data model self.position to update cell
}

现在,您可以随时调用refreshCellInfo,而无需传递参数。