Objective-C 内存管理
来源:互联网 发布:在github上下载源码 编辑:程序博客网 时间:2024/06/05 09:37
Objective-C 内存管理
首先申明下,本文为笔者学习《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];}@endint main(int argc, const char* argv[]) {Shape* shape = [Shape new];[shape retain]; // retainCount = 2NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape release]; // retainCount = 1NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape retain]; // retainCount = 2NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape release]; // retainCount = 1NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape release]; // retainCount = 0return 0;}
2、自动释放池
自动释放池是用来存放对象的集合,并且能够自动释放。(1) 创建自动释放池
通过@autoreleasepool关键字
通过NSAutoReleasePool对象
(2) autorelease方法
将对象添加到自动释放池,当自动释放池销毁时,会向池中对象发送release消息。
- (id) autorelease;(3) 简单例子
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 = 2NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape release]; // retainCount = 1NSLog(@"releaseing pool");[pool release];@autoreleasepool {Shape* shape = [Shape new]; // retainCount = 1[shape retain]; // retainCount = 2[shape autorelease]; // retainCount = 2NSLog(@"Shape retainCount = %lu", [shape retainCount]);[shape release]; // retainCount = 1NSLog(@"releaseing pool");}return 0;}
3、自动引用计数ARC
启动ARC以后,编译器会帮你插入retain和release语句,就像自己手动写好了所有的内存管理代码。
在项目的Build Settings选项卡中,启动ARC,默认是YES的。
启动ARC后,不能调用对象的内存管理方法:
- retain
- retainCount
- release
- autorelease
- dealloc
阅读全文
0 0
- objective-c内存管理
- Objective-c 内存管理
- Objective-C内存管理~~
- Objective-C内存管理
- Objective-C 内存管理
- Objective-C 内存管理
- Objective-C 内存管理
- Objective-C内存管理
- objective-c 内存管理
- objective-c 内存管理
- Objective-C 内存管理
- Objective-C内存管理
- Objective-C 内存管理
- objective-c内存管理
- objective-c内存管理
- Objective-c 内存管理
- Objective-C 内存管理
- Objective-C 内存管理
- TP下页面通过Ajax获取控制器中的数据
- 51 linux设备驱动的proc调用接口
- Linux中提示No such file or directory解决方法
- 网络爬虫---1.简介
- Drag-and-Drop——拖拽
- Objective-C 内存管理
- SAX方法解析XML文件
- linux 下调用opencv接口函数实现鼠标在窗口画方框操作
- Android禁止输入表情符号的EditText
- CDN(内容分发网络)技术原理
- hadoop之map读取数据流程
- ros catkin_make 出现add_custom_target cannot create target 错误
- TCP三次握手连接及seq和ack号的正确理解
- BZOJ 3622 已经没有什么好害怕的了