Values in Objective-C

Our first example will demonstrate various value types in Objective-C, including strings, integers, floats, and booleans. Here’s the full source code:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // Strings, which can be concatenated with stringWithFormat:
        NSString *result = [NSString stringWithFormat:@"%@%@", @"objective", @"-c"];
        NSLog(@"%@", result);
        
        // Integers and floats
        NSLog(@"1+1 = %d", 1 + 1);
        NSLog(@"7.0/3.0 = %f", 7.0 / 3.0);
        
        // Booleans, with boolean operators as you'd expect
        NSLog(@"%d", YES && NO);
        NSLog(@"%d", YES || NO);
        NSLog(@"%d", !YES);
    }
    return 0;
}

To run the program, save it as values.m and use the following commands:

$ clang -framework Foundation values.m -o values
$ ./values
objective-c
1+1 = 2
7.0/3.0 = 2.333333
0
1
0

Let’s break down the code:

  1. We import the Foundation framework, which provides essential Objective-C classes.

  2. The main function is the entry point of our program.

  3. We use an @autoreleasepool block to manage memory automatically.

  4. For string concatenation, we use NSString’s stringWithFormat: method.

  5. We use NSLog to print output, which is similar to printf but automatically adds a newline.

  6. For numbers and arithmetic operations, we use standard C syntax.

  7. Boolean values in Objective-C are represented by YES and NO.

  8. Boolean operations use the same operators as in C: && for AND, || for OR, and ! for NOT.

This example demonstrates basic value types and operations in Objective-C. Note that Objective-C combines elements of C with object-oriented extensions, which is why you see a mix of C-style syntax and Objective-C objects and methods.