Reputation:
I'm supposed to create a c++ class with c++ methods, that are made of objective-c and use cocoa, but now I've ran into a problem, and simply can't figure it out, cause I'm pretty new at objective-c. Also the point is that I should be able to create windows and buttons from c++. So when ever I build and run this program, it starts up but then instantly turns into a "not responding" state. Anyways, here's what I got:
Window.h
#ifndef WINDOW_H
#define WINDOW_H
class Window {
public:
Window();
void createButton();
};
#endif
Window.mm
#include "Window.h"
#include "Button.h"
Window::Window(){
NSWindow *window = [[NSWindow alloc]
initWithContentRect: NSMakeRect(100, 100, 200, 200)
styleMask: NSTitledWindowMask | NSMiniaturizableWindowMask
backing: NSBackingStoreBuffered
defer: NO];
[window setTitle: @"Test window"];
}
void Window::createButton(){
Button *button;
[[this contentView] addSubView: button];
// word this gives warning: no '-addSubView:' method found
// this is probably causing the problem I have
}
Button.h
class Button{
Button();
};
// There will be more methods here eventually
Button.mm
#include "Button.h"
Button::Button(){
NSButton *button = [[NSButton alloc]
initWithFrame: NSMakeRect(14, 100, 120, 40)];
[button setTitle: @"Hello world"];
[button setAction: @selector(invisible)];
[button setBezelStyle: NSRoundedBezelStyle];
[button setButtonType: NSMomentaryLightButton];
[button setBezelStyle: NSTexturedSquareBezelStyle];
}
Main.cpp
#include "Window.h"
#include "Button.h"
int main(int argc, char *argv[]){
Window x;
x.createButton();
}
So, does anyone have any idea why ain't it working, like I mentioned, I'm pretty new at Cocoa and Objective-C, still learning :P And yeah, I've tried to fix it.
Upvotes: 3
Views: 1387
Reputation: 1614
[[this contentView] addSubView: button];
As you suspect, that is causing your problem. "This" is not referring to the window; it refers to the class itself. (Remember, your class is not a subclass of an NSWindow)
One option is to declare your NSWindow in the header so it can be used globally. So make your header:
#ifndef WINDOW_H
#define WINDOW_H
class Window {
public:
Window();
void createButton();
NSWindow *window;
};
#endif
And then change the aforementioned line to:
[[window contentView] addSubview: button];
(Also notice to fix the capitalization on 'addSubview')
It's a similar problem with your button constructor. You are creating an NSButton, but that button is never seen or heard from again.
Upvotes: 3
Reputation: 36143
Your main
function is not running the run loop, so the drawing and event handling systems will be non-responsive.
You never show the window you created.
I don't see where you save away the Cocoa objects so that your C++ API can manipulate them. For example, your Window
constructor does not save the created window to a member variable, so you will have no way to manipulate that window after its creation.
Upvotes: 3