8

Objective-C をサポートするために、最近 *.cpp から *.mm に名前を変更した C++ クラスがあります。したがって、次の Objective-C コードを追加できます。

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationHandler:) 
                                                 name:@"notify"
                                               object:nil];
  • c++ で notificationHandler メソッドを作成するにはどうすればよいですか?
  • addObserver:self プロパティの設定は機能しますか?
4

3 に答える 3

18

または、ブロックを使用して次のことを行うこともできます。

[
    [NSNotificationCenter defaultCenter] addObserverForName: @"notify"
    object: nil
    queue: nil
    usingBlock: ^ (NSNotification * note) {
        // do stuff here, like calling a C++ method
    }
];
于 2014-09-18T01:20:08.187 に答える
16

Objective-C 通知を処理するには、Objective-C クラスが必要です。コア ファウンデーションが救出に向かう!

In.. コンストラクターなど、通知のリッスンを開始する場所:

static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);

MyClass::MyClass() : {
    // do other setup ...

    CFNotificationCenterAddObserver
    (
        CFNotificationCenterGetLocalCenter(),
        this,
        &notificationHandler,
        CFSTR("notify"),
        NULL,
        CFNotificationSuspensionBehaviorDeliverImmediately
    );
}

完了したら、たとえばデストラクタで:

MyClass::~MyClass() {
    CFNotificationCenterRemoveEveryObserver
    (
        CFNotificationCenterGetLocalCenter(),
        this
    );
}

最後に、ディスパッチを処理する静的関数:

static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    (static_cast<MyClass *>(observer))->reallyHandleTheNotification();
}

タダ!

于 2011-05-19T17:24:43.987 に答える
4

Objective-C メソッドが C++ に対してメソッド呼び出しを処理する方法のため、C++ メソッドをオブザーバーとして追加することはできません。これらのメソッドに応答するには、Objective-C クラス ( @interface Class..で宣言) が必要です。@end

唯一のオプションは、C++ クラスを Objective-C クラスでラップするか、オブジェクトへの参照だけを持ち、通知が到着したら静的にメソッドを呼び出す非常に軽いラッパーを使用することです。

于 2011-05-19T17:17:50.977 に答える