Search code examples
cnswindowobjective-c-runtime

Subclassing in Objective C Runtime


I am attempting to implement a solution from How to set canBecomeKeyWindow? Into my native C application using Objective-C runtime (The app is already written with objective C Runtime). Is there a way to create a subclass purely in Objective-C Runtime?

Right now I just create NSWindow object but need to be able to create my own so I can override the function specified in that question.

objc_msgSend((id)objc_getClass("NSWindow"), sel_registerName("alloc"));

Solution

  • Figured it out after a lot of code searching:

            // Subclass NSWindow with overridden function
            Class __NSWindow =
                objc_allocateClassPair(objc_getClass("NSWindow"), "__NSWindow", 0);
            class_addMethod(__NSWindow,
                            sel_registerName("canBecomeKeyWindow"),
                            (IMP)can_become_key_window_true, "B@:");
            objc_registerClassPair(__NSWindow);
    
            // Allocate a new __NSWindow
            window = objc_msgSend((id)__NSWindow, sel_registerName("alloc"));
    

    And then can_become_key_window_true is defined as:

    static bool can_become_key_window_true() {
        return true;
    }
    

    I use objc_allocateClassPair to subclass the object and return a Class of that object. Then I use class_addMethod to override the method canBecomeKeyWindow. And finally use objc_registerClassPair to register my new class before using it as I would a normal NSWindow.