为什么 [NSCursor IBeamCursor] 为空?

why [NSCursor IBeamCursor] is null?

问题是 [NSCursor IBeamCursor] returns 对我来说是空的。 你可以试试:

clang main.m -framework AppKit

来源:

#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;
}

AppKit 需要对其许多类型进行一定量的初始化才能挂接到系统事件、应用程序生命周期、事件路由等。看来 NSCursor 是其中一种类型。

通常,AppKit 应用程序调用 NSApplicationMain() 来触发初始化和 运行 应用程序,但这通常不适合命令行应用程序,因为 NSApplicationMain 也会触发加载主应用 nib/storyboard,然后接管执行。

如果您需要此功能而不显示 UI,您可以通过调用 +[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.

调用其中任何一个都可以让您初始化 NSCursor 而无需任何其他 UI。