如何在Cocoa中读取环境变量?

时间:2021-09-30 10:55:21

How could I read an environmental variable that a user has set?

我怎样才能读取用户设置的环境变量?

I'm new to desktop development on the Mac (cocoa), and I am building a little tool that I can use to access amazon's s3 service.

我是Mac(可可)桌面开发的新手,我正在构建一个可用于访问亚马逊s3服务的小工具。

I set my environmental variables in my .bash_profile, but I want this to work regardless of where the user entered it (.bashrc, .bash_profile or .profile etc).

我在.bash_profile中设置了我的环境变量,但无论用户输入的位置如何(.bashrc,.bash_profile或.profile等),我希望它能够正常工作。

2 个解决方案

#1


17  

Look at the environment method on a NSProcessInfo. It returns a NSDictionary of the environment so e.g. for PATH

查看NSProcessInfo上的环境方法。它返回环境的NSDictionary,例如对于PATH

NSString* path = [[[NSProcessInfo processInfo]environment]objectForKey:@"PATH"];

#2


5  

You can use a C API from the GNU library http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

您可以使用GNU库中的C API http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

converting to NSString: modern obj-c:

转换为NSString:现代obj-c:

NSString *envVarString = @(getenv("__MY_ENV_NAME__"));

legacy obj-c:

NSString *envVarString = [NSString stringWithUTF8String: getenv("__MY_ENV_NAME__")];

#1


17  

Look at the environment method on a NSProcessInfo. It returns a NSDictionary of the environment so e.g. for PATH

查看NSProcessInfo上的环境方法。它返回环境的NSDictionary,例如对于PATH

NSString* path = [[[NSProcessInfo processInfo]environment]objectForKey:@"PATH"];

#2


5  

You can use a C API from the GNU library http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

您可以使用GNU库中的C API http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access

converting to NSString: modern obj-c:

转换为NSString:现代obj-c:

NSString *envVarString = @(getenv("__MY_ENV_NAME__"));

legacy obj-c:

NSString *envVarString = [NSString stringWithUTF8String: getenv("__MY_ENV_NAME__")];