C的内存管理MRC与ARC

Objective-c中提供了两种内存管理机制MRC(MannulReference Counting)和ARC(Automatic Reference Counting),分别提供对内存的手动和自动管理,来满足不同的需求。注意的是Xcode 4.1及其以前版本没有ARC,MRC与ARC的区别如图1所示。需要理解MRC,但实际使用时强推ARC

C的内存管理MRC与ARC

图1  MRC与ARC区别示意图

 

1. Objective-c语言中的MRC(MannulReference Counting) 

在MRC的内存管理模式下,与对变量的管理相关的方法有:retain,release和autorelease。retain和release方法操作的是引用记数,当引用记数为零时,便自动释放内存。并且可以用NSAutoreleasePool对象,对加入自动释放池(autorelease调用)的变量进行管理,当drain时回收内存。

(1)      retain,该方法的作用是将内存数据的所有权附给另一指针变量,引用数加1,即retainCount+= 1;

(2)      release,该方法是释放指针变量对内存数据的所有权,引用数减1,即retainCount-= 1;

(3)      autorelease,该方法是将该对象内存的管理放到autoreleasepool中。

示例代码:

//假设Number为预定义的类

Number* num = [[Number alloc] init];

Number* num2 = [num retain];//此时引用记数+1,现为2

[num2 release]; //num2 释放对内存数据的所有权 引用记数-1,现为1;

[num release];//num释放对内存数据的所有权 引用记数-1,现为0;

[num add:1 and 2];//bug,此时内存已释放。

//autoreleasepool 的使用 在MRC管理模式下,我们摒弃以前的用法,NSAutoreleasePool对象的使用,新手段为@autoreleasepool

@autoreleasepool {

Number* num = [[Number alloc] init];

[numautorelease];//由autoreleasepool来管理其内存的释放

对与Objective-c中属性的标识符可以总结为:

@property (nonatomic/atomic,retain/assign/copy, readonly/readwrite) Number* num;

(1)      nonatomic/atomic,表示该属性是否是对多线程安全的,是不是使用线程锁,默认为atomic,

(2)      retain/assign/copy,是有关对该属性的内存管理的,

l  assign"is the default. In the setter that is created by @synthesize, the value willsimply be assigned to the attribute, don’t operate the retain count. Myunderstanding is that "assign" should be used for non-pointer attributes.

l  "retain"is needed when the attribute is a pointer to an object. The setter generated by@synthesize will retain (aka add a retain count) the object. You will need torelease the object when you are finished with it.

l  "copy"is needed when the object is mutable. Use this if you need the value of theobject as it is at this moment, and you don't want that value to reflect anychanges made by other owners of the object. You will need to release the objectwhen you are finished with it because you are retaining the copy.

(3)      readwrite /readonly -"readwrite" is the default. When you @synthesize, both a getter and asetter will be created for you. If you use "readonly", no setter willbe created. Use it for a value you don't want to ever change after the instantiationof the object.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/893b56acbdf013a10d42a4a9fcc7f7d9.html