潜在的内存泄漏或错误的引用计数减少

时间:2012-10-29 16:11:36

标签: objective-c memory-management

我有这个方法

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        UIWebView *t_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 
                                                                       320,480)];
        self.webView = t_webView;
        self.accel = [[Accelerometer alloc]init];

        //Potential Memory Leak here
        NSURL *theurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"html" inDirectory:@"www"]];
        [self.webView loadRequest:[NSURLRequest requestWithURL:theurl]];
        [self.view addSubview:webView];

        [theurl release];//When I add this line, the Memory Leak Warning disappears, but instead I get a "incorrect Decrement of reference count
        theurl = nil;

        [t_webView release];
    }

    return self;
 }

我认为我对内存管理一无所知,有人可以帮助我避免警告吗?

1 个答案:

答案 0 :(得分:2)

NSURL *theurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"html" inDirectory:@"www"]];

返回一个自动释放的对象。 release稍后在方法中使用它是不正确的。

泄漏是self.accel = [[Accelerometer alloc]init];; + alloc意味着retain,保留属性的赋值是另一个。我建议:

Accelerometer *acc = [[Accelerometer alloc]init];
self.accel = acc;
... do stuff with `acc` ...
[acc release];

如果编译器警告来了,那就是[theurl release],这听起来像是一个分析器错误。