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 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
- ››Mac 下搭建Android开发环境
- ››iphone图片拉伸的几种方法
- ››iphone正则表达式的简单使用
- ››Mac OS X 10.7.3安装Xcode3.2.6解决方案
- ››Mac QTMovieView添加划入窗口
- ››iPhone开发Unresolved Symbols CAKeyframeAnimati...
- ››IPhone开发-“此证书是由未知颁发机构签名”解决方...
- ››IPhone开发-整合私钥和证书,生成.p12文件
- ››iPhone应用开发-UIPickerView选取器详解
- ››iphone 获取屏幕的宽度和高度
- ››iPhone读取工程包中的二进制文件
- ››iPhone新手机 不挂YouTube APP
更多精彩
赞助商链接