0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · Lesson

Manual Retain-Release (MRR) Basics

Understand the principles of manual memory management, including retain, release, and autorelease pools.

Manual Retain-Release (MRR) Basics is a free Objective-C iOS Development for Legacy & Enterprise Apps lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Objective-C iOS Development for Legacy & Enterprise Apps learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome to Memory Management

In Objective-C, managing memory is crucial for efficient and stable apps. Before Automatic Reference Counting (ARC) became standard, developers manually handled memory using a system called Manual Retain-Release (MRR).

Understanding MRR helps you work with older codebases and grasp the fundamentals of how ARC works behind the scenes.

What is Reference Counting?

MRR is based on reference counting. Every object has a 'retain count', which is an integer that tracks how many 'owners' an object currently has.

  • When an object is created, its retain count is 1.
  • When an object gains an owner, its retain count increases.
  • When an object loses an owner, its retain count decreases.
  • When the retain count drops to 0, the object is deallocated (destroyed).

Taking Ownership with `retain`

To indicate that you want to keep an object in memory, you send it a retain message. This increases its retain count by one.

Think of it as saying, 'I need this object, don't let it disappear yet!'

Try running this example:

#import <Foundation/Foundation.h>

@interface MyObject : NSObject
@end

@implementation MyObject
- (id)init {
    self = [super init];
    if (self) {
        NSLog(@"MyObject created. Retain count: %lu", [self retainCount]);
    }
    return self;
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MyObject *obj = [[MyObject alloc] init]; // Retain count is 1
        [obj retain]; // Retain count becomes 2
        NSLog(@"After retain: %lu", [obj retainCount]);

        // Note: We'll learn about 'release' soon!
    }
    return 0;
}

Releasing Ownership with `release`

When you no longer need an object you own, you must send it a release message. This decreases its retain count by one.

If the retain count drops to zero, the object is deallocated, freeing up its memory. Failing to release objects you own leads to memory leaks.

#import <Foundation/Foundation.h>

@interface MyObject : NSObject
@end

@implementation MyObject
- (id)init {
    self = [super init];
    if (self) {
        NSLog(@"MyObject created. Retain count: %lu", [self retainCount]);
    }
    return self;
}
- (void)dealloc {
    NSLog(@"MyObject deallocated.");
    [super dealloc]; // Always call super's dealloc
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MyObject *obj = [[MyObject alloc] init]; // Retain count 1
        [obj retain]; // Retain count 2
        NSLog(@"After retain: %lu", [obj retainCount]);

        [obj release]; // Retain count 1
        NSLog(@"After first release: %lu", [obj retainCount]);
        [obj release]; // Retain count 0, object deallocated
    }
    return 0;
}

The `dealloc` Method Explained

The dealloc method is a special method that gets called automatically when an object's retain count reaches zero, just before its memory is reclaimed.

You implement dealloc in your custom classes to perform cleanup tasks, such as releasing instance variables that you own, removing observers, or closing file handles.

#import <Foundation/Foundation.h>

@interface MyClass : NSObject {
    NSString *_name;
}
- (id)initWithName:(NSString *)name;
@end

@implementation MyClass
- (id)initWithName:(NSString *)name {
    self = [super init];
    if (self) {
        _name = [name retain]; // Retain the name string
        NSLog(@"MyClass '%@' initialized. Retain count: %lu", _name, [self retainCount]);
    }
    return self;
}

- (void)dealloc {
    NSLog(@"MyClass '%@' is being deallocated.", _name);
    [_name release]; // Release instance variables you own
    _name = nil;     // Set to nil to prevent dangling pointers
    [super dealloc]; // Always call super's dealloc LAST
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MyClass *myObject = [[MyClass alloc] initWithName:@"Coddy"];
        // Do something with myObject
        [myObject release]; // Release the object when done
    }
    return 0;
}

MRR Ownership Rules

The golden rule for MRR is simple:

  • You own any object you create (using alloc, new, copy, or mutableCopy).
  • You own any object you explicitly retain.
  • You must release any object you own when you are done with it.

If you receive an object from a method that doesn't start with 'alloc', 'new', 'copy', or 'mutableCopy', you generally don't own it and shouldn't release it (unless you explicitly retain it).

Introducing `autorelease`

Sometimes, you need to return an object from a method, but you don't want the caller to have to immediately release it. This is where autorelease comes in.

When you send an object an autorelease message, its retain count is decreased at some point in the future, typically when the current autorelease pool is drained.

It's like saying, 'I'm done with this, but don't deallocate it just yet; let the system handle its eventual release.'

Working with Autorelease Pools

autorelease works with NSAutoreleasePool. Objects marked autorelease are added to the current pool. When the pool is 'drained', all objects in it receive a release message.

In modern Objective-C, you use the @autoreleasepool block syntax. This ensures that temporary objects are released efficiently, preventing memory accumulation.

#import <Foundation/Foundation.h>

@interface MyObject : NSObject
@end

@implementation MyObject
- (id)init {
    self = [super init];
    if (self) {
        NSLog(@"MyObject created.");
    }
    return self;
}
- (void)dealloc {
    NSLog(@"MyObject deallocated.");
    [super dealloc];
}
@end

MyObject *createAndAutoreleaseObject() {
    MyObject *obj = [[MyObject alloc] init];
    NSLog(@"Object retain count before autorelease: %lu", [obj retainCount]);
    return [obj autorelease]; // Defer release until pool drains
}

int main(int argc, const char * argv[]) {
    NSLog(@"Before autoreleasepool block");
    @autoreleasepool {
        NSLog(@"Inside autoreleasepool block");
        MyObject *a = createAndAutoreleaseObject();
        // 'a' is valid here
        NSLog(@"Object retain count after autorelease: %lu", [a retainCount]);
    }
    NSLog(@"After autoreleasepool block. Object should be deallocated.");
    return 0;
}

MRR Best Practices

Writing correct MRR code requires discipline:

  • Balance `retain` and `release` calls: For every retain, alloc, new, copy, or mutableCopy, there must be a corresponding release or autorelease.
  • Don't over-release: Releasing an object more times than it was retained will lead to a crash.
  • Release instance variables in `dealloc`: Make sure to release any objects you retained as instance variables.
  • Call `[super dealloc]` last: In your dealloc method, always call the superclass's dealloc at the very end.

MRR Concepts Check

Consider the following Objective-C code snippet:


NSString *myString = [[NSString alloc] initWithFormat:@"Hello"];
[myString retain];
// ... some operations ...
[myString release];
// ... more operations ...
[myString release];

What is the final state of myString after both release calls, assuming it started with a retain count of 1 from alloc?

Recap: MRR Fundamentals

You've explored the core principles of Manual Retain-Release (MRR):

  • Reference Counting: Objects track ownership with a retain count.
  • `retain`: Increases an object's retain count, indicating ownership.
  • `release`: Decreases an object's retain count; deallocates when count reaches 0.
  • `dealloc`: A special method for cleanup when an object is destroyed.
  • `autorelease`: Defers an object's release until an autorelease pool is drained.

Mastering these basics is key to understanding legacy Objective-C code and the underlying mechanisms of modern memory management!

Frequently asked questions

Is the “Manual Retain-Release (MRR) Basics” lesson free?

Yes — the full text of “Manual Retain-Release (MRR) Basics” is free to read here on the web, and the Objective-C iOS Development for Legacy & Enterprise Apps course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Objective-C iOS Development for Legacy & Enterprise Apps course, upgrade to CoddyKit PRO.

What will I learn in “Manual Retain-Release (MRR) Basics”?

Understand the principles of manual memory management, including retain, release, and autorelease pools. You practise Objective-C iOS Development for Legacy & Enterprise Apps with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Objective-C iOS Development for Legacy & Enterprise Apps?

No prior experience is required. Objective-C iOS Development for Legacy & Enterprise Apps on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Manual Retain-Release (MRR) Basics” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Objective-C iOS Development for Legacy & Enterprise Apps lesson?

Yes. Every Objective-C iOS Development for Legacy & Enterprise Apps lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Manual Retain-Release (MRR) Basics
  2. Automatic Reference Counting (ARC)
  3. Weak vs. Strong References
  4. Breaking Retain Cycles in Blocks
← Back to Objective-C iOS Development for Legacy & Enterprise Apps