Environment Variables in Objective-C

Our program demonstrates how to work with environment variables in Objective-C. Here’s the full source code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // To set a key/value pair, use setEnvironmentVariable:forKey:
        // To get a value for a key, use getenv()
        // This will return NULL if the key isn't present in the environment.
        
        setenv("FOO", "1", 1);
        NSLog(@"FOO: %s", getenv("FOO"));
        NSLog(@"BAR: %s", getenv("BAR") ? getenv("BAR") : "");
        
        // Use NSProcessInfo to list all key/value pairs in the environment.
        // This returns an NSDictionary of all environment variables.
        // Here we print all the keys.
        
        NSLog(@"");
        NSDictionary *env = [[NSProcessInfo processInfo] environment];
        for (NSString *key in env) {
            NSLog(@"%@", key);
        }
    }
    return 0;
}

To set a key/value pair, we use the setenv function. To get a value for a key, we use the getenv function. This will return NULL if the key isn’t present in the environment.

We use NSProcessInfo to list all key/value pairs in the environment. This returns an NSDictionary of all environment variables. Here we print all the keys.

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 ./environment-variables
FOO: 1
BAR: 2
...

This example demonstrates how to interact with environment variables in Objective-C, which is a common way to pass configuration information to programs.