Objective-C 内存管理

it2022-05-05  136

首先申明下,本文为笔者学习《Objective-C 基础教程》的笔记,并加入笔者自己的理解和归纳总结。

1. 引用计数法

Objective-C采用引用计数的技术,当访问一个对象时,该对象的保留计数器值加一。当结束对象访问时,将对象的保留计数器值减一。 当使用alloc、new方法或者通过copy创建一个对象时,对象的保留计数器值被设置为1。要增加保留计数器值,调用retain方法。要减少的话,调用release方法。 当一个对象的保留计数器值归零时,会调用dealloc方法。

@interface Shape : NSObject @end @implementation Shape - (id) init { if (self = [super init]) { NSLog(@"Shape init retainCount = %lu", [self retainCount]); } return self; } - (void) dealloc{ NSLog(@"Shape dealloc called"); [super dealloc]; } @end int main(int argc, const char* argv[]) { Shape* shape = [Shape new]; [shape retain]; // retainCount = 2 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape release]; // retainCount = 1 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape retain]; // retainCount = 2 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape release]; // retainCount = 1 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape release]; // retainCount = 0 return 0; }

输出

Shape init retainCount = 1 Shape retainCount = 2 Shape retainCount = 1 Shape retainCount = 2 Shape retainCount = 1 Shape dealloc called

2. 自动释放池

自动释放池是用来存放对象的集合,并且能够自动释放。

创建自动释放池

通过@autoreleasepool关键字 通过NSAutoReleasePool对象

autorelease方法

将对象添加到自动释放池,当自动释放池销毁时,会向池中对象发送release消息。

- (id) autorelease;

简单例子

int main(int argc, const char* argv[]) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; Shape* shape = [Shape new]; // retainCount = 1 [shape retain]; // retainCount = 2 [shape autorelease]; // retainCount = 2 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape release]; // retainCount = 1 NSLog(@"releaseing pool"); [pool release]; @autoreleasepool { Shape* shape = [Shape new]; // retainCount = 1 [shape retain]; // retainCount = 2 [shape autorelease]; // retainCount = 2 NSLog(@"Shape retainCount = %lu", [shape retainCount]); [shape release]; // retainCount = 1 NSLog(@"releaseing pool"); } return 0; }

输出

Shape init retainCount = 1 Shape retainCount = 2 releaseing pool Shape dealloc called Shape init retainCount = 1 Shape retainCount = 2 releaseing pool Shape dealloc called

3. 自动引用计数ARC

启动ARC以后,编译器会帮你插入retain和release语句,就像自己手动写好了所有的内存管理代码。 在项目的【Build Settings】选项卡中,启动【ARC】,默认是YES的。 启动ARC后,不能调用对象的内存管理方法:

retainretainCountreleaseautoreleasedealloc

源码下载: https://github.com/nai-chen/ObjCBlog

相关文章 Objective-C 类 Objective-C 数据类简介 Objective-C 内存管理 Objective-C 对象初始化 Objective-C 属性值 Objective-C 类别 Objective-C 协议 Objective-C 异常、选择器、代码块 Objective-C 键值编码 Objective-C 谓词


最新回复(0)