經過多年的Java開發,我開始在Objective-C中編程。我正在苦苦掙扎的一個問題是內存管理。特別是,書籍和在線的大多數例子似乎都沒有考慮到由於例外而造成的內存泄漏。例如,考慮下面的方法:我應該將[pool drain]放在@finally子句中嗎?
-(void) doSomething
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
// Allocate some autoreleased objects here
NSString *data = [NSString [email protected]"Hello"];
// Do some work, exception could be thrown
[PotentialExeptionThrower maybeThrowException];
// Clean up autorelease objects
[pool drain];
}
不應上述改寫爲防止任何潛在的內存泄漏?
-(void) doSomething
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
@try {
// Allocate some autoreleased objects here
NSString *data = [NSString [email protected]"Hello"];
// Do some work, exception could be thrown
[PotentialExeptionThrower maybeThrowException];
} @finally {
// Clean up autorelease objects
[pool drain];
}
}
由於@ try- @ catch,上面的代碼效率低嗎?
謝謝!
感謝您的鏈接,我發現你的博客文章非常有幫助。你對Java背景是正確的。異常處理是Java編程中不可分割的一部分,我用@try @catch @finally填充我的Objective-C代碼。我現在開始琢磨正確的模式。 – 2010-12-12 17:54:17