gpt4 book ai didi

macos - 在 MacOSX 10.5 上作为启动守护程序运行时, bundle 路径返回空

转载 作者:行者123 更新时间:2023-12-03 18:00:04 25 4
gpt4 key购买 nike

我有一个 Cocoa 命令行应用程序,它是针对 10.5 SDK 构建的。在应用程序中,我有

NSString *appPath = [[NSBundle mainBundle] bundlePath];
NSLog(@"%@", appPath);

在 Mac OSX 10.5 上,当我从命令行运行应用程序时,我得到了路径的预期输出。但是,如果我将应用程序设置为作为 LaunchDeamon 运行,它只会输出“/”

它作为守护进程和应用程序在 10.6 和 10.7 上按预期工作。有谁知道为什么会有差异?有没有更好的方法来获取适用于 10.5+ 的应用程序路径?

更新

对我来说,已接受答案中的解决方案不起作用。然而,关于将“WorkingDirectory”键添加到 LaunchDeamon 的 plist 文件中的评论成功了。显然,Mac OS X 10.5 需要此功能,但 10.6+ 则不需要。

最佳答案

感谢您回答我的澄清问题。

NSBundle 依赖于现有的 bundle ,及其关联的 Info.plists 和 bundle ID(例如 com.apple.textedit.app)等。

虽然单个二进制文件不是 bundle ,但我猜测 Apple 工程人员修复了 [[NSBundle mainBundle] bundlePath] 在 10.6 和 10.7 中做“正确的事情”。但您仍然需要 10.5 的解决方案。

也许是 UNIX 库函数 char * getcwd(char *buf, size_t size)会带你去你需要去的地方。

为了获得正确的解决方案,我建议使用如下所示的代码进行运行时条件检查:

+ (NSString *) getAppPath
{
NSString * appPath = NULL;
SInt32 minorVersionNum;
OSErr err;

err = Gestalt(gestaltSystemVersionMinor,&minorVersionNum);

// do this only if we're running on anything *older* than 10.6
if((noErr == err) && (minorVersionNumber < 6))
{
// hopefully the below define is enough space for any returned path
#define kMaxPathLength 512

size_t bufferLength = kMaxPathLength;
char bufferToHoldPath[kMaxPathLength];

// initialize the buffer & guarantee null-terminated strings
bzero(&bufferToHoldPath,bufferLength);
if( getcwd(&bufferToHoldPath, bufferLength) != NULL)
{
appPath = [NSString stringWithUTF8String: bufferToHoldPath];
}
}

// this code runs for 10.6 and *newer*, and attempts it on
// 10.5 only if the above getcwd call failed
if(NULL == appPath)
{
appPath = [[NSBundle mainBundle] bundlePath];
}

return(appPath);
}

我没有没有测试这段代码,所以 YMMV。

关于macos - 在 MacOSX 10.5 上作为启动守护程序运行时, bundle 路径返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8085987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com