I'm building a cross platform app, and 1 of those platforms is Macos.
Now the core of my code is written in C++, and Obj-C++.
I create a window like this:
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(x, y, width, height) styleMask:macosWindowStyle backing:NSBackingStoreBuffered defer:false];
but I wanted to listen to the window. I could've subclassed it, but I chose not to.
The other way to get events from the NSWindow
was to set a delegate.
Now since my code was in Obj-C++, I couldn't have a C++ class inherit from a Obj-C protocol.
So, I created a Obj-C header, which implemented NSWindowDelegate
.
Here it is:
@interface SomeClass : NSObject<NSWindowDelegate>
@end
I overrode windowShouldClose
as such:
- (BOOL)windowShouldClose:(NSWindow *)sender {
NSLog(@"Hello!");
return true;
}
and in my Obj-C++ file, I did this:
NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(x, y, width, height) styleMask:macosWindowStyle backing:NSBackingStoreBuffered defer:false];
SomeClass* someClass = [[SomeClass alloc] init];
[window setDelegate:someClass];
However, when I pressed the X button, nothing happened.
I then proceeded to test the same thing in Swift, same result.
I then realized that the delegate was being destroyed because it was a weak reference.
My question is, how do I get around this?
OK, I figured it out. I for some reason thought I could not have Obj-C class pointers in my Obj-C++ code. I thought that was one of the limitations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.