Objective-C lesson 2 内存管理-自动释放池的工作过程
// // main.m // RetainCount // // Created by Waqar Malik on 3/30/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface RetainTracker : NSObject @end // RetainTracker @implementation RetainTracker - (id) init { if (self = [super init]) { NSLog (@"init: Retain count of %lu.", [self retainCount]); } return (self); } // init - (void) dealloc { NSLog (@"dealloc called. Bye Bye."); [super dealloc]; } // dealloc @end // RetainTracker int main(int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; RetainTracker *tracker = [RetainTracker new]; // count: 1 [tracker retain]; // count: 2 [tracker autorelease]; // count: still 2 [tracker release]; // count: 1 NSLog (@"releasing pool"); [pool release]; // gets nuked, sends release to tracker //autoreleasepool RetainTracker *tracker2 = [RetainTracker new]; // count: 1 [tracker2 retain]; // count: 2 [tracker2 autorelease]; // count: still 2 [tracker2 release]; // count: 1 NSLog (@"auto releasing pool");
//autoreleasepool
return (0); }
运行结果:
init: Retain count of 1.
releasing pool
dealloc called.Bye Bye.
你可能已经猜到,释放自动释放池之前的NSLog函数比RetainTracker类中的NSLog()函数先被调用。
PS:还有一点大家需要注意,就是清理自动释放池,比如下面的代码:
View Code
int i; for (i = 0; i < 1000000; i++) { id object = [someArray objectAtIndex: i]; NSString *desc = [object description]; // and do something with the description }
这个循环创建了100万个字符串对象,所有这些对象都被放进当前自动释放池的话就会产生100万个闲置的字符串,并一直存在直到自动释放池销毁时才释放。解决方法如下面的代码:
View Code
NSAutoreleasePool *pool; pool = [[NSAutoreleasePool alloc] init]; int i; for (i = 0; i < 1000000; i++) { id object = [someArray objectAtIndex: i]; NSString *desc = [object description]; // and do something with the description if (i % 1000 == 0) { [pool release]; pool = [[NSAutoreleasePool alloc] init]; } } [pool release];
循环每执行1000次,新的自动释放池就被销毁,同时有一个更新的被创建。
请注意,如果开发iPhone软件,则不能使用垃圾回收。实际上,在编写iPhone程序时,苹果公司建议你不要在自己的代码中使用autorelease方法,同时还要避免使用创建自动释放对象的便利函数。
posted on 2012-07-03 15:52 MichaelZhao 阅读(414) 评论(0) 编辑 收藏 举报