内存管理总结
iPhone系统中的Objective-C的内存管理机制是比较灵活的,即可以拿来像C/C++一样用,也可以加个AutoreleasePool让它升级为半自动化的内存管理语言。当然,也不能拿JAVA虚拟机中的全自动化GC来比~
一,引用计数是实例对象的内存回收唯一参考
引用计数(retainCount)是Objective-C管理对象引用的唯一依据。调用实例的release方法后,此属性减一,减到为零时对象的dealloc方法被自动调用,进行内存回收操作,也就是说我们永不该手动调用对象的dealloc方法。
它的内存管理API老简单老简单了,下面就是它主要操作接口:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSObject *o = [[NSObject alloc] init]; //retainCount为1 [o retain]; //retainCount为2 [o release]; //retainCount为1 [o autorelease]; //retainCount为1 [pool release]; //retaincount为0,触发dealloc方法
三,对象的拥有者
面向对象领域里有个引用的概念,区别于继承,引用常被用来当做偶合性更小的设计。继承是强依赖,对吧。我们要降偶软件的设计,就要尽量减少对它的使用。但没有任何偶合的模块或功能是没有用的~对吧,那我们只能多用引用了吧。一个实例拥有另一个实例的时候,我们称它为引用了另一个实例。
比如ClassA类的一个属性对象的Setter方法:
- (void)setMyArray:(NSMutableArray *)newArray { if (myArray != newArray) { [myArray release]; myArray = [newArray retain]; } }
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];int retVal = UIApplicationMain(argc, argv, nil, nil);[pool release];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSObject *o = [[NSObject alloc] init]; [o autorelease]; //在pool实例dealloc时,release一次此实例,重要的是并不是在此行去release NSLog(@"o retainCount:%d",[o retainCount]); //此时还可以看到我们的o实例还是可用的,并且retainCount为1 [pool release]; //pool 的 retainCount为0,自动调用其dealloc方法,我们之前备案的小o也将在这里release一次(因为咱们之前仅仅autorelease一次)
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSObject *o = [[NSObject alloc] init]; [o retain]; [o autorelease]; [o autorelease]; [pool release];
NSAutoreleasePool *pool1 = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init]; NSAutoreleasePool *pool3 = [[NSAutoreleasePool alloc] init]; NSObject *o = [[NSObject alloc] init] autorelease]; [pool3 release]; [pool2 release]; [pool1 release];