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:
We import the Foundation framework, which provides essential Objective-C classes.
The
main
function is the entry point of our program.We use an
@autoreleasepool
block to manage memory automatically.For string concatenation, we use
NSString
’sstringWithFormat:
method.We use
NSLog
to print output, which is similar toprintf
but automatically adds a newline.For numbers and arithmetic operations, we use standard C syntax.
Boolean values in Objective-C are represented by
YES
andNO
.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.