来拔点草
今天看到个autorelease twice的问题,整了一下,发现一点坑,包含单例、局部常量。
首先,autorelease调多少次,就往pool加多少次,到时候就release多少次,文档有,不必说。
然后,重点来了:NSString *str = [[NSString alloc] init]; 这货release多少次都不crash。。
stack上有:
http://stackoverflow.com/questions/9068883/accessing-a-released-nsstring-doesnt-make-the-app-crash
代码测试,alloc多个string,他们的地址确实是一样的,果然是单例。继续测了一下NSNumber alloc init,竟然是0x0,不觉明厉。。
然后,测format的情况,多次release还是不crash,估计把字符串当成常量,所以怎么release都没用。不过,先用autorelease,再release,runloop结束时就crash鸟,嗯,局部常量是在函数栈里面,退出就被销毁,故当pool释放时,str再release就crash了。
同上,测NSNumber各种initWith,发现obj = initWithInt,然后obj = initWithDouble,两个地址一样,单例无疑,release自然没用,继续同样的加autorelease,跟str一样crash,嗯,因为int/double也都是栈的。值得注意的是initWithBOOL,传YES和NO生成的是不同地址,不再是单例。