I'm trying to run native object-c code on my Mac application.
My code looks like:
MainWindow.h:
#ifdef Q_OS_MAC
#include <Carbon/Carbon.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <mach/mach_port.h>
#include <mach/mach_interface.h>
#include <mach/mach_init.h>
#include <IOKit/pwr_mgt/IOPMLib.h>
#include <IOKit/IOMessage.h>
#endif
MainWindow.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
#ifdef Q_OS_MAC
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
selector: @selector(receiveSleepNote:)
name: NSWorkspaceWillSleepNotification object: NULL];
#endif
}
#ifdef Q_OS_MAC
- (void) receiveSleepNote: (NSNotification*) note
{
NSLog(@"receiveSleepNote: %@", [note name]);
}
#endif
But am getting errors that seems that QT does not understand the code structure:
application.cpp: error: expected external declaration - (void) receiveSleepNote: (NSNotification*) note ^
In order to compile objective-c with C++, you need to have the objective-c code in a .m or .mm file.
The accompanying header can then contain functions that can be called from C++ and the body of those functions can contain objective-c code.
So let's say, for example, we wanted to call a function to pop up an OSX notification. Start with the header: -
#ifndef __MyNotification_h_
#define __MyNotification_h_
#include <QString>
class MyNotification
{
public:
static void Display(const QString& title, const QString& text);
};
#endif
As you can see, this is a regular function in a header that can be called from C++. Here's the implementation:-
#include "mynotification.h"
#import <Foundation/NSUserNotification.h>
#import <Foundation/NSString.h>
void MyNotification::Display(const QString& title, const QString& text)
{
NSString* titleStr = [[NSString alloc] initWithUTF8String:title.toUtf8().data()];
NSString* textStr = [[NSString alloc] initWithUTF8String:text.toUtf8().data()];
NSUserNotification* userNotification = [[[NSUserNotification alloc] init] autorelease];
userNotification.title = titleStr;
userNotification.informativeText = textStr;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}
The implementation contains objective-c and due to its .mm file extension, the compiler will handle this correctly.
Note that in the example you provide in the question, you need to think about what the code is doing; especially when using 'self', as I expect that would need to refer to an Objective-C class, not a C++ class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With