Home > Software design >  why [NSCursor IBeamCursor] is null?
why [NSCursor IBeamCursor] is null?

Time:09-16

The problem is that [NSCursor IBeamCursor] returns null for me. You can try:

clang main.m -framework AppKit

source:

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <AppKit/NSWindow.h>

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    NSCursor * c = [NSCursor IBeamCursor];
    NSLog(@"IBeamCursor = %p %@", c, c);
  }
  return 0;
}

CodePudding user response:

AppKit requires some amount of initialization for many of its types to hook into system events, app lifecycle, event routing, etc. It appears that NSCursor is one of these types.

Typically, an AppKit application calls NSApplicationMain() to trigger that initialization and run the application, but this typically isn't appropriate for a command-line application as NSApplicationMain also triggers loading the main app nib/storyboard, and then takes over execution.

If you need this functionality without showing a UI, you can trigger this either by calling [NSApplication sharedApplication] or NSApplicationLoad():

  • sharedApplication:

    This method also makes a connection to the window server and completes other initialization. Your program should invoke this method as one of the first statements in main(); this invoking is done for you if you create your application with Xcode.

  • NSApplicationLoad:

    You typically call this function before calling other Cocoa code in a plug-in loaded into a primarily Carbon application. If the shared NSApplication object isn’t already initialized, this function initializes it and sets up the necessary event handlers for Cocoa.

Calling either one will allow you to initialize your NSCursor without any other UI.

  • Related