WEB开发网
开发学院手机开发iPhone 开发 iPhone/Mac Objective-C内存管理教程和原理剖析 阅读

iPhone/Mac Objective-C内存管理教程和原理剖析

 2010-05-29 05:52:00 来源:WEB开发网   
核心提示:");NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];NSLog(@"create an instance of ClassA and autorelease");ClassA *obj1 = [[[ClassA all
");

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSLog(@"create an instance of ClassA and autorelease ");

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

NSDate *now = [[NSDate alloc] init];

NSTimer *timer = [[NSTimer alloc] initWithFireDate:now

interval:0.0

target:obj1

selector:@selector(createClassB)

userInfo:nil

repeats:NO];

NSRunLoop *runLoop = [NSRunLoop currentRunLoop];

[runLoop addTimer:timer forMode:NSDefaultRunLoopMode];

[timer release];

[now release];

[runLoop run]; //在新loop中调用一函数,生成ClassB的autorelease实例

NSLog(@"releasing autorelasePool ");

[pool release];

NSLog(@"autorelasePool is released ");

return 0;

}

输出如下:

create an autorelasePool

create an instance of ClassA and autorelease

create an instance of ClassB and autorelease

ClassB destroyed

releasing autorelasePool

ClassA destroyed

autorelasePool is released

注意在我们销毁autorelease pool之前,ClassB的autorelease实例就已经被销毁了。

有人可能会说,这并不能说明新的run loop自动生成了一个新的autorelease pool,说不定还只是用了老的autorelease pool,只不过后来drain了一次而已。我们可以在main函数中不生成autorelease pool。精简的示例代码如下,详细代码请见附件中的memman-run-loop-without-pool.m。

int main(int argc, char**argv)

{

NSLog(@"No autorelasePool created ");

NSLog(@"create an instance of ClassA ");

ClassA *obj1 = [[ClassA alloc] init];

NSDate *now = [[NSDate alloc] init];

NSTimer *timer = [[NSTimer alloc] initWithFireDate:now

interval:0.0

target:obj1

selector:@selector(createClassB)

userInfo:nil

上一页  2 3 4 5 6 7 8  下一页

Tags:iPhone Mac Objective

编辑录入:coldstar [复制链接] [打 印]
赞助商链接