Objective-C Note

Hello World

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSLog(@"Hello World!");
    }
    return 0;
}

Comments

// single line comment

/*
  Multi-lines
  comment
*/

Variables

#import <Foundation/Foundation.h>

#define My_constant_var 31337

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        int my_var = 42;
        NSLog(@"%d",my_var);
        NSLog(@"%d",My_constant_var);
    }
    return 0;
}

Shorthand assignment

a += b # a = a + b
a -= b # a = a - b
a *= b # a = a * b
a /= b # a = a / b
a %= b # a = a % b
a **= b # a = a**b

Input

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSFileHandle *inputHandle = [NSFileHandle fileHandleWithStandardInput];
        NSData *data = [NSData dataWithData:[inputHandle availableData]];
        NSString *input = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSLog(@"%@", input);
    }
    return 0;
}

Array

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSArray *peoples = @[@"Alice", @"Bob", @"Eve"];
        NSLog(@"%@", peoples[0]);   // Output: Alice
        NSLog(@"%@", peoples[1]);   // Output: Bob
        NSLog(@"%@", peoples[2]);   // Output: Eve
        
        NSMutableArray *foo = [NSMutableArray arrayWithObjects:@42, @"Cindy", @0.02, @YES, nil];
        [foo addObject:@"d"];
        [foo addObject:@1337];
        [foo insertObject:@0.05 atIndex:2];
        
        [foo removeLastObject];
        [foo removeObjectAtIndex:2];
        
        NSLog(@"%@", foo);
        NSLog(@"%@", foo);
        
        NSArray *alph = @[@"a", @"c", @"z", @"e"];
        NSLog(@"%@", [alph subarrayWithRange:NSMakeRange(1, 3)]);

        NSArray *x = @[@41, @53];
        NSArray *y = @[@72, @16, @133];
        NSArray *res = [x arrayByAddingObjectsFromArray:y];
        res = [y arrayByAddingObjectsFromArray:x];
        NSArray *z = @[@16, @41, @55];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT SELF IN %@", z];
        res = [res filteredArrayUsingPredicate:predicate];
        
        NSLog(@"%@", res);
    }
    return 0;
}