首页 文章

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

提问于
浏览
1

我对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 回答

  • 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 而无需传递参数 .

相关问题