今天随便写了一个测量代码运行时间的小程序,代码是这样的:
NSDate* d1=[NSDate date]; //dosomthing NSDate* d2=[NSDate date]; NSLog(@"time: %f",[d2 timeIntervalSinceDate:d1]);
当我通过 run->console 查看日志输出时,出现了" *** _NSAutoreleaseNoPool(): Object 0x36acd0 of class NSCFDate autoreleased with no pool in place - just leaking" 。
对于Autorelease的对象,如果没有AutoreleasePool的话,就会提示内存泄露的错误。可问题是我怎么知道哪些对象是Autorelease的,哪些不是呢?在此发现了一个规律:如果对象不是用[[object alloc] init(withXXX)] 创建的,就是Autorelease的。
正确的写法:
NSAtuoreleasePool* pool=[NSAutoreleasePool new]; NSDate* d1=[NSDate date]; //dosomthing NSDate* d2=[NSDate date]; NSLog(@"time: %f",[d2 timeIntervalSinceDate:d1]); [pool drain]