2017-04-17 6 views
1

編集:解決済み、下記の私の解決策を参照してください。私はそれがなぜ機能するかについてはまだ興味がありますが、おそらくあなたの解決策はこれを説明することができますか?Swift 3オプションのプロトコル用バインド

通知センター通知を使用してオブジェクトを渡しています。

私の目標は、特定のに準拠する場合は、notification.objectをオプションでアンラップすることです。

問題はテスト中ですが、アンラップが失敗していることがわかりましたが、なぜその理由がわかりません。

NotificationsPipelineProtocolに付着し、それらの通知にサブスクライブ受信オブジェクトへの通知と一緒にこれらのオブジェクトを送信する(時にはenumstruct)オブジェクトの一連。

だから例えば私は通知パイプラインにしてReleaseNoteを渡した場合、私はそれは、プロトコルに加入する必要があります:私はNotificationCenterに加入するすべての項目に書かれた拡張機能を投稿したい

enum ReleaseNote: Float, NotificationsPipelineProtocol { 
    ... 

NotificationsPipelineProtocolに呼び出されます:

// finishing task, wants to post completion 
    ... 
     self.postCompletion() 
    ... 

func postCompletion() { 
     NotificationCenter.default.post(name: self.completionNotificationName, object: self) 
    } 
この関数を呼び出します

私はこの機能を使用して適切に受け取ったことを保証しています

@objc private func didReceiveNotificationCompletion(_ notification : Notification) { 

    guard let completedNotification = notification.object as? NotificationsPipelineProtocol else { 
     return 
    } 

しかしreturnが実行されるため、上記のガード文は、オプションをアンラップと結合しません。

私はnotification.objectをコンソールに印刷しましたが、実際に目的のオブジェクトを受け取っていることを保証しています。

なぜそれが開かれないのでしょうか?

+0

NSValueまたはNSNumberで.objectがラップされていませんか。実行時にプロパティクラスをチェックしてください。 –

+0

私はコンソールに印刷すると '_SwiftValue'という結果が出る – achi

+0

NSObjectプロトコルのいくつかの種類にブリッジする必要があるかもしれませんか? NotificationCenterがObjective-Cに橋渡しされていることを認めていますか? – achi

答えて

1

私はオブジェクトからuserInfoへのパイプラインオブジェクトへのアクセスを置き換えることで解決しました。

これがどうして必要なのか、私は完全にはわかりませんが、うまくいきます。

オブジェクト

guard let userInfo = notification.userInfo, 
      let completedNotification = userInfo["pipelineItem"] as? NotificationsPipelineProtocol else { 
     return 
    } 
0

は、多分あなたは間違ったオブジェクトを送信/観察しているこのワークフローですべての問題があってはならないの取得対象

func postCompletion() { 
     NotificationCenter.default.post(name: self.completionNotificationName, object: nil, userInfo: ["pipelineItem": self]) 
    } 

投稿?

ここでは、遊び場で使用できるようにしようとしているものの例を示します。失敗点を見つけるまで、コードを遊び場/サンプルプロジェクトに移動してみてください。

//: Playground - noun: a place where people can play 

import Foundation 
import PlaygroundSupport 

PlaygroundPage.current.needsIndefiniteExecution = true 

protocol NotificationsPipelineProtocol { 

} 

class TestObserver: NotificationsPipelineProtocol { 

    init() { 
     NotificationCenter.default.addObserver(self, 
               selector: #selector(notificationFired(_:)), 
               name: nil, 
               object: self) 
    } 

    dynamic func notificationFired(_ notification: Notification) { 
     guard let object = notification.object as? NotificationsPipelineProtocol else { 
      return 
     } 

     print("success") 
    } 

    func fireNotification() { 
     NotificationCenter.default.post(name: Notification.Name(rawValue: "test"), object: self) 
    } 

} 

let observer = TestObserver() 
observer.fireNotification() 
+0

私は同意する必要はありません。しかし、これは..私はあなたのコードをサンドボックスで試してみることを考えますが、あなたが上に見たものはコードで書かれているものなので、結果が大きく異なるとは想像できません – achi

関連する問題