NSUserNotification from pure C++

373 Views Asked by At

I am trying to post a UserNotification from pure C++. I am basing my code off of this SO answer: https://stackoverflow.com/a/14083212/5548305

Right now I am having trouble setting a value for object properties. I am sure there is something I am missing. I was trying to leverage setValue:forKey but I can't find any documentation on it. I have searched through objc-runtime.h and obj.h but could not find anything that jumped out at me. Has anyone tried/succeeded at this?

#include <CoreFoundation/CoreFoundation.h>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <iostream>    

int main(int argc, char** argv)
{    

    id app = NULL;


    id notif = (id)objc_getClass("NSUserNotification");
    notif = objc_msgSend(notif, sel_registerName("alloc"));
    notif = objc_msgSend(notif, sel_registerName("init"));
    notif = sel_setValue(CFSTR("title"), id("title"));      <-This line here


    objc_msgSend(pool, sel_registerName("release"));
    return 0;
}
2

There are 2 best solutions below

1
On BEST ANSWER

Does that code actually compile? Apple's documentation of the Objective-C runtime has become much worse in recent years but I don't recall and can't find any mention of a sel_setValue.

-setValue:forKey: is just a regular message like any other, so I'd expect something more like:

objc_msgSend(notif, sel_registerName("setValue:forKey:"), 
             CFSTR("title"), CFSTR("title"))

On the grounds that objc_msgSend takes a variable number of arguments, the first two being the target object and the selector, and the rest being the various other arguments to the method. Target key names are supplied as strings, they're mapped to properties internally, with a few different combinations tried, and in this case the property also expects to hold a string.

The declared return type for setValue:forKey: is void so there's no return value to catch.

0
On

If anyone in the future is trying to accomplish this, I did end up getting this to work and made a project on github showing how to post an NSUserNotification in pure C.

https://github.com/jslegendre/NS-C-UserNotification