linyawen

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

转自http://www.cnblogs.com/MobileDevelop/archive/2010/07/19/1779138.html

如果你能够真正的理解autorelease, 那么你才是理解了Objective c的内存管理。Autorelease实际上只是把对release的调用延迟了,对于每一个Autorelease, 系统只是把该Object放入了当前的Autorelease pool中, 当该pool被释放时,该pool中的所有Object会被调用Release。

那什么是一个Runloop呢? 一个UI事件,Timer call, delegate call, 都会是一个新的Runloop。例子如下:
 
NSString* globalObject;
- (void)applicationDidFinishLaunching:(UIApplication *)application 
{    
globalObject = [[NSString alloc] initWithFormat:@"Test"];
NSLog(@"Retain count after create: %d", [globalObject retainCount]); // output 1.
[globalObject retain];
NSLog(@"Retain count after retain: %d", [globalObject retainCount]); // output 2.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(@"Retain count after Button click runloop finished: %d", [globalObject retainCount]); 
// 输出1. Button click loop finished, it's autorelease pool released, globalObject get released once.
}
-(IBAction)onButtonClicked
{
[globalObject autorelease];
NSLog(@"Retain count after autorelease: %d", [globalObject retainCount]); 
        // 输出2。 Autorelease被call, globalObject被加如当前的AutoreleaePool。 
}

ClassA *Func1()

{

  ClassA *obj = [[[ClassA alloc]init]autorelease];

  return obj;

}

posted on 2012-05-09 17:51  linyawen  阅读(263)  评论(0编辑  收藏  举报