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
原创粉丝点击