xcode Mac 应用默认工作目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4521151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mac app default working directory
提问by toastie
I've made many apps in Xcode before and always their default working directory was the one where the .app file is, so I've accessed the internal data like Whatever.app/Contents/Resources. I know it's probably not the right way, but it has always worked. Anyway, either from a recent Xcode update or for some other reason, their default working folder is now being set to "/". This only happens when I run the .app file from Finder. If I run it from within Xcode, the folder path is correct (I can set that path in the executable options, but it has no effect on what happens when you run the .app directly). Is this a setting somewhere or just the new standard?
我以前在 Xcode 中制作了许多应用程序,并且它们的默认工作目录始终是 .app 文件所在的目录,因此我访问了诸如 What.app/Contents/Resources 之类的内部数据。我知道这可能不是正确的方法,但它一直有效。无论如何,无论是最近的 Xcode 更新还是其他原因,他们的默认工作文件夹现在都设置为“/”。这仅在我从 Finder 运行 .app 文件时发生。如果我从 Xcode 中运行它,文件夹路径是正确的(我可以在可执行选项中设置该路径,但它对直接运行 .app 时发生的情况没有影响)。这是某个地方的设置还是只是新标准?
回答by
For resources, use this cool code:
对于资源,使用这个很酷的代码:
NSString *path = [[NSBundle mainBundle] pathForResource:@"awesomepic" ofType:@"png"];
You should never depend on PWD with Cocoa. Instead, use Cocoa API's whenever possible. BSD API's should only be used if Apple provided no other way.
你永远不应该依赖可可的 PWD。相反,尽可能使用 Cocoa API。仅当 Apple 没有提供其他方式时才应使用 BSD API。
globheader.h
globheader.h
static char *appdir;
appcontroller.m
appcontroller.m
#import "globheader.h"
@implementation AppController
- (void)method {
appdir = [[[NSBundle mainBundle] bundlePath] UTF8String];
}
@end
cppcode.cpp
cppcode.cpp
#include "globheader.h"
int main() {
printf("%s", appdir);
return 0;
}
回答by Cesar A. Rivas
toastie, why use the application bundle to store data? don't change your .app.
toastie,为什么要使用应用程序包来存储数据?不要更改您的 .app。
Instread, use the application support folder. You can modify the bytes in that folder with no problems. Read the following post from Matt Gallagher,
Instread,使用应用程序支持文件夹。您可以毫无问题地修改该文件夹中的字节。阅读 Matt Gallagher 的以下帖子,
http://cocoawithlove.com/2010/05/finding-or-creating-application-support.html
http://cocoawithlove.com/2010/05/finding-or-creating-application-support.html
regards,
问候,