수동 보존-해제(MRR) 기초
retain, release 및 자동 해제 풀을 포함한 수동 메모리 관리의 원리를 이해합니다.
수동 보존-해제(MRR) 기초은(는) CoddyKit의 무료 Objective-C iOS Development for Legacy & Enterprise Apps 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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, ormutableCopy). - You own any object you explicitly
retain. - You must
releaseany 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, ormutableCopy, there must be a correspondingreleaseorautorelease. - 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
deallocmethod, always call the superclass'sdeallocat 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!
자주 묻는 질문
“수동 보존-해제(MRR) 기초” 강의는 무료인가요?
네 — “수동 보존-해제(MRR) 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Objective-C iOS Development for Legacy & Enterprise Apps 강의 전체를 잠금 해제할 수 있습니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“수동 보존-해제(MRR) 기초”에서 뭘 배우나요?
retain, release 및 자동 해제 풀을 포함한 수동 메모리 관리의 원리를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Objective-C iOS Development for Legacy & Enterprise Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Objective-C iOS Development for Legacy & Enterprise Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Objective-C iOS Development for Legacy & Enterprise Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“수동 보존-해제(MRR) 기초” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Objective-C iOS Development for Legacy & Enterprise Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 수동 보존-해제(MRR) 기초
- 자동 참조 카운팅(ARC)
- 약한 참조와 강한 참조
- 블록의 유지 순환 끊기