0

当我必须释放一个对象时,我在某些情况下感到困惑?所以我想知道我们什么时候在目标C中释放对象。我可以在分配对象的地方使用自动释放自动释放的任何缺点吗?在哪里释放以下对象?

情况1:

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

案例二:

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];
4

2 回答 2

2

是的,您必须为上述两种情况释放。

情况1:

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

案例二:

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意思?Autorelease 意味着,不是我们,而是我们的 App 将决定何时释放该对象。假设您的问题的案例2。barView添加到之后self.view就不需要这个分配的对象了。因此,我们发布它。但是,如果我们将它保持在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;
}

解决方案

使用 ARC,忘记retain release:)

于 2012-10-12T07:06:03.100 回答
1

如果在 3 种情况下使用ARC ,则无需释放任何东西,只需明智地使用(如果需要,分配)

如果不使用 ARC,则需要释放

现在案例1:

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

案例二:

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链接。

于 2012-10-12T07:06:17.657 回答