2012-10-12 52 views
0

當我必須釋放一個對象時,我在某些情況下感到困惑嗎?所以我想知道什麼時候在Objective C中釋放對象。我可以使用autorelease在哪裏分配對象autorelease的任何缺點?在哪裏發佈以下對象?目標釋放對象C

案例1:

SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil]; 
[[self navigationController] pushViewController:obj animated:YES]; 

案例2:

UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)]; 
barView.backgroundColor=[UIColor redColor]; 
[self.view addSubview:barView]; 

案例3:

NSURLRequest *request = [NSURLRequest requestWithURL: 
         [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

回答

2

是的,你必須釋放對於上述兩種情況。

案例1:

SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil]; 
[[self navigationController] pushViewController:obj animated:YES]; 
[obj release]; 

案例2:

UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)]; 
barView.backgroundColor=[UIColor redColor]; 
[self.view addSubview:barView]; 
[barView release]; 

案例3:

NSURLRequest *request = [NSURLRequest requestWithURL: 
        [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]]; 
[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

你並不需要在這裏釋放,因爲請求對象處於自動發佈模式。

記住兩件事。

1.)當您的對象爲retainalloc-init時,您必須手動釋放對象。

2.)沒有alloc方法的類方法返回autoreleased對象,因此您不需要釋放這些對象。

使用autorelease的缺點:

好了,這是什麼意思autorelease?自動釋放意味着,而不是我們,但我們的應用程序將決定何時釋放對象。假設你的問題的情況2。在將barView添加到self.view後,不需要此分配的對象。因此,我們釋放它。但是,如果我們將它保存在autorelease模式中,則應用程序將保留更長時間,通過仍保留該對象來浪費部分內存。因此,我們不應該在這裏使用autorelease。

使用autorelease的優勢:

該過流行的例子。

- (NSString*) getText 
{ 
    NSString* myText = [[NSString alloc] initWithFormat:@"Hello"]; 
    return myText; 
} 

這裏,3號線引起的泄漏,因爲我們不釋放分配給myText內存。 因此,

- (NSString*) getText 
{ 
    NSString* myText = [[[NSString alloc] initWithFormat:@"Hello"] autorelease]; 
    return myText; 
} 

SOLUTION

使用ARC,忘記retainrelease :)

+0

謝謝你回答,我還有一個問題,我使用JSON和幾個對象顯示內存泄漏JSON SDK .m文件?當我啓用ARC,然後這些文件顯示我錯誤。如何在ARC上使用JSON sdk – QueueOverFlow

+0

我對使用的代碼瞭解不多。但你可以谷歌這樣的事情。 http://stackoverflow.com/questions/8701780/using-non-arc-code-in-an-arc-enabled-project-adding-facebook – mayuur

1

如果3例使用ARC然後沒有必要釋放那些僅僅使用明智地(ALLOC如果需要)

如果不使用ARC,那麼它需要釋放

現在的情況下1:

SelectFrame *obj=[[SelectFrame alloc]initWithNibName:@"SelectFrame" bundle:nil]; 
[[self navigationController] pushViewController:obj animated:YES]; 
[obj release]; 

案例2:

UIView *barView=[[UIView alloc]initWithFrame:CGRectMake(0, 500, 200,50)]; 
barView.backgroundColor=[UIColor redColor]; 
[self.view addSubview:barView]; 
[barView release]; 

案例3:

NSURLRequest *request = [NSURLRequest requestWithURL: 
        [NSURL URLWithString:@"https://xxxxxxxxxxxxxxxxx"]]; 
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease]; 

參考,How-to-avoid-memory-leaks-in-iPhone-applications鏈接。