一位新同事的代码,老是内存泄露,找不到问题,我就帮忙看了一下,最后找到问题是在dealloc 中将UIButton的对象release了。
一般情况,UIButton初始化一般使用静态方法+ (id)buttonWithType:(UIButtonType)buttonType; 而非alloc或者create方法。只有在使用alloc与create关键字的方法下创建对象才会使此对象的retain值+1,而release是使retain-1,所以在创建UIButton之后是不需要release的。
所以,通过静态方法初始化而非alloc的对象一般可以认为是autorelease的。
One new guy told me his codes always leaked, and he could not find the problems. The problem was he released a UIButton object in the dealloc method, after I checked his codes. Generally, we use the static method '+ (id)buttonWithType:(UIButtonType)buttonType;' to initialise a UIButton, not alloc or create. The alloc method makes retainCount +1, while 'release' makes it -1. Therefore, the new guy's UIButton is no need to release.
About all, we can treat the object, created by static methods not the alloc, as autoreleased one.