Variables in Objective-C

Our first example demonstrates how to declare and use variables in Objective-C. Here’s the full source code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // NSString variable declaration and initialization
        NSString *a = @"initial";
        NSLog(@"%@", a);
        
        // Multiple variable declaration and initialization
        int b = 1, c = 2;
        NSLog(@"%d %d", b, c);
        
        // BOOL variable declaration and initialization
        BOOL d = YES;
        NSLog(@"%d", d);
        
        // Integer variable declaration without initialization
        int e;
        NSLog(@"%d", e);
        
        // NSString variable declaration and initialization
        NSString *f = @"apple";
        NSLog(@"%@", f);
    }
    return 0;
}

In Objective-C, variables are explicitly declared with their types. Let’s break down the example:

  • NSString *a = @"initial"; declares and initializes a string variable.
  • int b = 1, c = 2; demonstrates declaring multiple variables of the same type in one line.
  • BOOL d = YES; shows how to declare and initialize a boolean variable.
  • int e; declares an integer variable without initialization. In Objective-C, uninitialized variables may contain garbage values, so it’s good practice to always initialize variables.
  • NSString *f = @"apple"; is another example of string variable declaration and initialization.

To run the program, save it as a .m file (e.g., variables.m) and compile it using the Objective-C compiler:

$ clang -framework Foundation variables.m -o variables
$ ./variables
initial
1 2
1
0
apple

Note that the output for the uninitialized variable e is 0 in this case, but this behavior is not guaranteed and can vary.

Objective-C uses static typing, which means you need to declare the type of a variable before using it. This helps catch type-related errors at compile-time rather than at runtime.

Unlike Go, Objective-C doesn’t have a shorthand syntax for variable declaration and initialization inside functions. You always need to specify the type explicitly.

Remember that when working with Objective-C objects (like NSString), you use pointers (*). For primitive types (like int, BOOL), you don’t use pointers.

Now that we’ve covered basic variable declaration and usage in Objective-C, let’s move on to more advanced concepts in the language.