0Pricing
Objective-C iOS Development for Legacy & Enterprise Apps · レッスン

手動Retain-Release(MRR)の基礎

retain、release、autoreleaseプールを含む、手動メモリ管理の原則を理解します。

「手動Retain-Release(MRR)の基礎」はCoddyKit上の無料Objective-C iOS Development for Legacy & Enterprise Appsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはObjective-C iOS Development for Legacy & Enterprise Apps学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Objective-C iOS Development for Legacy & Enterprise Appsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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!

よくある質問

「手動Retain-Release(MRR)の基礎」レッスンは無料ですか?

はい。「手動Retain-Release(MRR)の基礎」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Objective-C iOS Development for Legacy & Enterprise Appsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Objective-C iOS Development for Legacy & Enterprise Appsコースには全4レッスンが含まれています。

「手動Retain-Release(MRR)の基礎」で何を学びますか?

retain、release、autoreleaseプールを含む、手動メモリ管理の原則を理解します。 ブラウザで直接実行するハンズオンコードでObjective-C iOS Development for Legacy & Enterprise Appsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Objective-C iOS Development for Legacy & Enterprise Appsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのObjective-C iOS Development for Legacy & Enterprise Appsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「手動Retain-Release(MRR)の基礎」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このObjective-C iOS Development for Legacy & Enterprise Appsレッスンでコードを書いて実行できますか?

はい。すべてのObjective-C iOS Development for Legacy & Enterprise Appsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 手動Retain-Release(MRR)の基礎
  2. 自動参照カウント(ARC)
  3. Weak参照とStrong参照
  4. ブロックによるretain cycleの解消
← Objective-C iOS Development for Legacy & Enterprise Appsに戻る