这是我第一次使用 Xcode,这个 IDE 完全不直观让我感到震惊。我听说过去更好,我真的希望如此。
我的问题是我的程序加载的资源,一个数据文件和一个 .ini 文件,它会自动在我的主文件夹中搜索这些文件。我想让它在 .app 的 Resource 文件夹中搜索这些文件。我正在使用 C++,我找到的所有示例都是针对 Objective-C 的。
知道如何解决这个问题吗?
最佳答案
您可能会假设,当您的应用程序启动时,进程的当前工作目录就是您的应用程序包。它不是。 (与 Xcode 无关——这就是 OS X 的工作方式。)
通常您会使用 NSBundle
( objective-c )或 CFBundle
(C)
在您的应用程序包中查找资源。由于您使用的是 C++,因此让我们使用 C API。
要在您的应用程序包的资源目录中找到文件“myFile.ini”的 URL:
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyResourceURL(mainBundle, CFSTR("myFile"), CFSTR("ini"), NULL);
UInt8 filePath[PATH_MAX];
if (CFURLGetFileSystemRepresentation(url, true, filePath, sizeof(filePath)))
{
// use your API of choice to open and read the file at filePath
}
或者,只需将 CWD 更改为您的应用程序包:
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyBundleURL(mainBundle);
UInt8 bundlePath[PATH_MAX];
if (CFURLGetFileSystemRepresentation(url, true, bundlePath, sizeof(bundlePath)))
{
if (chdir((const char*)bundlePath) == 0)
{
// now the CWD is your app bundle, and you can use relative path names to access files inside it
}
}
关于c++ - Xcode 从我的主文件夹而不是资源加载程序资源 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9765925/