Objective-C Reference
0. Basics
0.1 Hello World
#import <Foundation/Foundation.h>
int main() {
@autoreleasepool {
// NSLog adds a timestamp and newline
NSLog(@"Hello, World!");
}
return 0;
}
TERMINAL OUTPUT
2024-05-16 12:00:00.000 main[123:456] Hello, World!
0.2 Building & Running
Use clang with the Foundation framework.
# Compile and run
clang -framework Foundation main.m -o main
./main
TERMINAL OUTPUT
Hello, World!
0.3 Comments
// Single-line comment
/* Multi-line
comment */
TERMINAL OUTPUT
(No output)
0.4 Imports
#import <Foundation/Foundation.h> // Smart include (prevents recursion)
#import "LocalHeader.h"
TERMINAL OUTPUT
(No output)
0.5 Exit Codes
#import <Foundation/Foundation.h>
// Standard C exit
exit(1);
TERMINAL OUTPUT
(Process exits with status 1)
0.6 Error Handling
@try {
@throw [NSException exceptionWithName:@"Fail" reason:@"Err" userInfo:nil];
} @catch (NSException *e) {
NSLog(@"Caught: %@", e.reason);
} @finally {
NSLog(@"Cleanup");
}
TERMINAL OUTPUT
Caught: Err
Cleanup
1. Environment & Time
1.1 Variable Declaration
NSString *name = @"ObjC"; // Object pointer
NSInteger count = 10; // Primitive (typedef to long or int)
BOOL active = YES; // Boolean (YES/NO)
TERMINAL OUTPUT
(No output)
1.2 Integer Types
NSInteger i = 100; // Signed (platform width)
NSUInteger u = 200; // Unsigned
int32_t i32 = 1000; // Fixed width (C99)
TERMINAL OUTPUT
(No output)
1.3 Casting
NSString *s = @"123";
NSInteger i = [s integerValue];
NSString *back = [NSString stringWithFormat:@"%ld", (long)i];
TERMINAL OUTPUT
(No output)
1.4 Truthiness
C-style truthiness. nil is falsy. Non-zero
primitives are truthy.
id obj = nil;
if (!obj) { NSLog(@"Object is nil"); }
int x = 1;
if (x) { NSLog(@"True"); }
TERMINAL OUTPUT
Object is nil
True
1.5 Environment Vars
NSDictionary *env = [[NSProcessInfo processInfo] environment];
NSString *path = env[@"PATH"];
TERMINAL OUTPUT
(No output)
1.6 Time
NSDate *now = [NSDate date];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@", [fmt stringFromDate:now]);
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)
2. Operators & Regex
2.1 Arithmetic/Logic
float a = 10 / 3.0;
BOOL b = YES && NO;
NSInteger c = 1 << 4; // 16
TERMINAL OUTPUT
(No output)
2.2 Regex
NSString *text = @"price: 100";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d+" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:text options:0 range:NSMakeRange(0, text.length)];
if (match) {
NSLog(@"%@", [text substringWithRange:match.range]);
}
TERMINAL OUTPUT
100
3. Argument Parsing
3.1 CLI Argument Parsing
NSArray *args = [[NSProcessInfo processInfo] arguments];
if (args.count > 1) {
NSLog(@"First arg: %@", args[1]);
}
TERMINAL OUTPUT
(Depends on input)
4. Functions & Memory
4.1 Declaration/Returns
// Method declaration (in @interface)
- (NSInteger)add:(NSInteger)a to:(NSInteger)b {
return a + b;
}
// C-style function
int multiply(int a, int b) { return a * b; }
TERMINAL OUTPUT
(No output)
4.2 References/Pointers
ARC (Automatic Reference Counting) manages object memory.
__strong NSString *s1 = @"Stay";
__weak NSString *s2 = s1; // Doesn't retain
__unsafe_unretained NSString *s3 = s1; // Dangling pointer potential
// POSIX memory
void *ptr = malloc(1024);
free(ptr);
TERMINAL OUTPUT
(No output)
5. Loops & Iteration
5.1 Basic Loops
for (int i = 0; i < 3; i++) { NSLog(@"%d", i); }
int x = 0;
while (x < 2) { x++; }
TERMINAL OUTPUT
0
1
2
5.2 Break/Continue
for (int i = 0; i < 5; i++) {
if (i == 1) continue;
if (i == 3) break;
NSLog(@"%d", i);
}
TERMINAL OUTPUT
0
2
5.3 Iterating Collections
NSArray *arr = @[@"a", @"b"];
for (NSString *s in arr) {
NSLog(@"%@", s);
}
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%lu: %@", (unsigned long)idx, obj);
}];
TERMINAL OUTPUT
a
b
0: a
1: b
6. Strings & Files
6.1 Manipulation
NSString *s = @" hello ";
NSString *trimmed = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *joined = [@[@"a", @"b"] componentsJoinedByString:@"-"];
TERMINAL OUTPUT
(No output)
6.2 Path Joining
NSString *path = [@"/tmp" stringByAppendingPathComponent:@"test.txt"];
TERMINAL OUTPUT
(No output)
6.3 Streaming I/O
NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:@"data.bin"];
NSData *chunk = [handle readDataOfLength:4096];
[handle closeFile];
TERMINAL OUTPUT
(No output)
6.4 Read to Memory
NSString *content = [NSString stringWithContentsOfFile:@"file.txt" encoding:NSUTF8StringEncoding error:nil];
NSData *data = [NSData dataWithContentsOfFile:@"file.txt"];
TERMINAL OUTPUT
(No output)
7. Binary & Bitwise
7.1 Allocation/Packing
NSMutableData *data = [NSMutableData dataWithCapacity:12];
int32_t val = 42;
[data appendBytes:&val length:sizeof(val)];
TERMINAL OUTPUT
(No output)
7.2 Bitwise Ops
int a = 0b1010 & 0b1100; // 8
int b = 0b1010 | 0b1100; // 14
int c = ~0b0001;
TERMINAL OUTPUT
(No output)
7.3 Hex Conversion
NSString *hex = [NSString stringWithFormat:@"%x", 255]; // "ff"
unsigned int val;
NSScanner *scanner = [NSScanner scannerWithString:@"ff"];
[scanner scanHexInt:&val]; // val = 255
TERMINAL OUTPUT
(No output)
8. Collections & JSON
8.1 Lists/Maps/Sets
NSArray *arr = @[@1, @2]; // Immutable Array
NSMutableArray *mArr = [arr mutableCopy]; // Mutable
NSDictionary *dict = @{@"key": @"val"}; // Literal Dictionary
NSSet *set = [NSSet setWithArray:@[@1, @1, @2]];
TERMINAL OUTPUT
(No output)
8.2 JSON Parsing
NSData *data = [@"{\"id\": 42}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json[@"id"]);
TERMINAL OUTPUT
42
9. Systems & Networking
9.1 TCP
// Using NSStream for Foundation-level TCP
NSInputStream *input;
NSOutputStream *output;
[NSStream getStreamsToHostWithName:@"localhost" port:8080 inputStream:&input outputStream:&output];
[input open]; [output open];
TERMINAL OUTPUT
(No output)
9.2 UDP
#import <sys/socket.h>
#import <netinet/in.h>
int sock = socket(AF_INET, SOCK_DGRAM, 0);
// Standard POSIX socket usage...
close(sock);
TERMINAL OUTPUT
(No output)
9.3 Concurrency
// Grand Central Dispatch (GCD)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"In background");
});
// NSOperationQueue
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"On main thread");
}];
TERMINAL OUTPUT
In background
On main thread
9.4 SQLite
#import <sqlite3.h>
sqlite3 *db;
sqlite3_open(":memory:", &db);
sqlite3_exec(db, "CREATE TABLE t(id INT)", NULL, NULL, NULL);
sqlite3_close(db);
TERMINAL OUTPUT
(No output)