Wie fügt man einen Beobachter für NSNotificationCenter in einer C ++ - Klasse mit objektiv-c ++ hinzu?
-
15-11-2019 - |
Frage
Hey Jungs Ich habe eine C ++ - Klasse, die ich kürzlich von * .cpp auf * .mm umbenannt habe, um objektive-c zu unterstützen.So kann ich den folgenden Objektiv-C-Code hinzufügen. generasacodicetagpre.
- .
- Wie schreibe ich / kann ich die notificationHandler-Methode in c ++ schreiben?
- setzt Addobserver ein: Selbsteigenschaftsarbeit?
Lösung
You'd need an Objective-C class to handle Objective-C notifications. Core Foundation to the rescue!
In.. wherever you start listening for notifications, e.g. your constructor:
static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);
MyClass::MyClass() : {
// do other setup ...
CFNotificationCenterAddObserver
(
CFNotificationCenterGetLocalCenter(),
this,
¬ificationHandler,
CFSTR("notify"),
NULL,
CFNotificationSuspensionBehaviorDeliverImmediately
);
}
When done, e.g. in your destructor:
MyClass::~MyClass() {
CFNotificationCenterRemoveEveryObserver
(
CFNotificationCenterGetLocalCenter(),
this
);
}
And finally, a static function to handle the dispatch:
static void notificationHandler(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
(static_cast<MyClass *>(observer))->reallyHandleTheNotification();
}
Ta da!
Andere Tipps
Or you could also just use blocks and do:
[
[NSNotificationCenter defaultCenter] addObserverForName: @"notify"
object: nil
queue: nil
usingBlock: ^ (NSNotification * note) {
// do stuff here, like calling a C++ method
}
];
You can't add a C++ method as an observer because of how Objective-C method handles method invocation vs C++. You must have an Objective-C class (Declared with @interface Class
.. @end
) to respond to those methods.
Your only option is to wrap your C++ class in an Objective-C class, or just have a very light wrapper that just has a reference to an object and calls a method statically once the notification arrives.