CodeToLive

Introduction to Objective-C

Objective-C is a powerful, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It was the primary language for Apple's macOS and iOS development before Swift.

Basic Syntax


// Hello World in Objective-C
#import <Foundation/Foundation.h>

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

Classes and Objects


// Interface (header file)
@interface Person : NSObject {
    NSString *_name;
    NSInteger _age;
}

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age;
- (void)introduce;

@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;

@end

// Implementation
@implementation Person

- (instancetype)initWithName:(NSString *)name age:(NSInteger)age {
    self = [super init];
    if (self) {
        _name = name;
        _age = age;
    }
    return self;
}

- (void)introduce {
    NSLog(@"My name is %@ and I'm %ld years old.", _name, (long)_age);
}

@end
            

Message Passing


Person *person = [[Person alloc] initWithName:@"John" age:30];
[person introduce];  // Message passing syntax
            

Memory Management

Objective-C uses Automatic Reference Counting (ARC) for memory management:


// With ARC (automatic)
NSString *string = [[NSString alloc] initWithFormat:@"Hello %@", @"World"];

// Without ARC (manual)
NSString *string = [[NSString alloc] initWithFormat:@"Hello %@", @"World"];
// ... use the string ...
[string release];  // Manual memory management
            

Categories

Add methods to existing classes without subclassing:


@interface NSString (Utilities)
- (BOOL)isPalindrome;
@end

@implementation NSString (Utilities)
- (BOOL)isPalindrome {
    NSString *lowercase = [self lowercaseString];
    NSUInteger length = [lowercase length];
    
    for (NSUInteger i = 0; i < length/2; i++) {
        if ([lowercase characterAtIndex:i] != 
            [lowercase characterAtIndex:length - 1 - i]) {
            return NO;
        }
    }
    return YES;
}
@end
            

Protocols

Similar to interfaces in other languages:


@protocol Printer <NSObject>
- (void)print;
@optional
- (void)prepareToPrint;
@end

@interface Document : NSObject <Printer>
@end

@implementation Document
- (void)print {
    NSLog(@"Printing document...");
}
@end
            

Foundation Framework

Key classes in Objective-C's Foundation framework:

Note: While Swift is now Apple's preferred language, understanding Objective-C is still valuable for maintaining legacy code and working with certain frameworks.

Next: Objective-C Syntax