问题
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.
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).
回答1:
Look at the environment method on a NSProcessInfo. It returns a NSDictionary of the environment so e.g. for PATH
NSString* path = [[[NSProcessInfo processInfo]environment]objectForKey:@"PATH"];
回答2:
You can use a C API from the GNU library http://www.gnu.org/software/libc/manual/html_node/Environment-Access.html#Environment-Access
converting to NSString: modern obj-c:
NSString *envVarString = @(getenv("__MY_ENV_NAME__"));
legacy obj-c:
NSString *envVarString = [NSString stringWithUTF8String: getenv("__MY_ENV_NAME__")];
来源:https://stackoverflow.com/questions/11550300/how-can-i-read-a-environmental-variable-in-cocoa