(2)尽量避免使用autorelease
虽然autorelease非常简单有用,但是在iphone上一定要谨慎使用,毕竟iphone内存相当有限.autorelease可能会导致直接的隐型内存泄露.
比如使用
NSString *string = [NSString stringWithFormat:@"value = %d", intVariable];
你可以换为
NSString *string = [[NSString alloc] initWithFormat:@"value = %d", intVariable];
...
[string release];
使用自动释放对象还有个坏处就是不便于开发者管理。增加程序崩溃的几率.
不过autorelease对象也不是一无是处。有时它的作用也很强大。
比如当你需要返回一个对象时就最好使用autorelease
(NSString *)AutoTest
{
return [[[NSString alloc] initWithFormat:@"value = %d", intVariable] autorelease];
}
你还可以在循环中使用autorelease pools
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (id item in array)
{
id anotherItem = [item createSomeAutoreleasedObject];
[anotherItem doSomethingWithIt];
}
[pool release];
注意:就我目前测试和观察看来。你只能在同一个函数中使用
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
和
[pool release];才能达到效果
最后一点就是:千万不要尝试去release一个auto对象。否则你的程序必然崩溃
待续......