手动保留与释放(MRR)基础
了解手动内存管理的原则,包括保留、释放和自动释放池。
手动保留与释放(MRR)基础 是 CoddyKit 上的免费 Objective-C iOS Development for Legacy & Enterprise Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!
用 AI 导师学习 Objective-C — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「手动保留与释放(MRR)基础」课时是免费的吗?
是的 — 「手动保留与释放(MRR)基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Objective-C iOS Development for Legacy & Enterprise Apps 课程的其余内容,请升级到 CoddyKit PRO。 Objective-C iOS Development for Legacy & Enterprise Apps 课程共包含 4 节课。
「手动保留与释放(MRR)基础」这节课中我会学到什么?
了解手动内存管理的原则,包括保留、释放和自动释放池。 你通过在浏览器中直接运行的动手代码来练习 Objective-C iOS Development for Legacy & Enterprise Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Objective-C iOS Development for Legacy & Enterprise Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Objective-C iOS Development for Legacy & Enterprise Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「手动保留与释放(MRR)基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Objective-C iOS Development for Legacy & Enterprise Apps 课中编写并运行代码吗?
能。每节 Objective-C iOS Development for Legacy & Enterprise Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 手动保留与释放(MRR)基础
- 自动引用计数(ARC)
- 弱引用与强引用
- 打破代码块中的保留环