You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么调用[NSCursor IBeamCursor]接口会返回null空值

你调用[NSCursor IBeamCursor]返回null的核心原因是AppKit的UI相关API必须在NSApplication初始化完成后才能正常调用,当前测试代码直接在main函数的自动释放池里调用该接口时,AppKit运行环境还未完成初始化,因此会返回空值。


修复方案

你只需要在调用NSCursor相关接口前,先完成NSApplication的初始化即可,修改后的测试代码如下:

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

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    // 先初始化NSApplication,完成AppKit运行环境准备
    [NSApplication sharedApplication];
    NSCursor * c = [NSCursor IBeamCursor];
    NSLog(@"IBeamCursor = %p %@", c, c);
  }
  return 0;
}

依旧使用原命令即可正常编译运行:

clang main.m -framework AppKit

运行后就能正常输出IBeamCursor的内存地址和对象信息,不会再返回null。


补充说明

所有AppKit框架下和UI渲染、交互相关的接口,都要求必须在NSApplication初始化之后调用。如果你是开发命令行工具需要用到NSCursor相关能力,只要加上[NSApplication sharedApplication]这行初始化代码即可,不需要额外配置窗口、启动事件循环。

内容的提问来源于stack exchange,提问作者pkirill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:30:02